Categories
discuss

Print only those numbers that are double of another number in the array in Java

I’m practicing algorithms and let’s say we have an array with elements 2, 3, 9, 12, 7, 18, then I want to print 18 only because it’s double of 9. When I print the result it always displays much more lines, however, the printed numbers (if there are any) are good. How can I manage displaying the result properly? (Using only arrays.) I know it’s a silly question but I tried so many ways and it was only worse.

Now, it shows me this for example (140 is correct, but the other line are not needed):

The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 140
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0

My code:

public class DoubleNums {

    public static void main(String[] args) {

        Random random = new Random();

        int[] array = new int[50];
        int[] even;
        int[] doubleNum;
        int count = 0;
        int doubles = 0;

        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(200);
            System.out.println(array[i] + " ");
        }
        for (int j = 0; j < array.length; j++) { 
            even = new int[array.length];
            if (array[j] % 2 == 0) {
                even[count] = array[j];
                count++;
            }
            for (int k = 0; k < array.length; k++) {
                doubleNum = new int[array.length];
                if (array[j] / 2 == array[k]) {
                    even[doubles] = k;
                    doubles++;
                    System.out.println("The following number is doubled of another number from the array: " + even[doubles]);               
                }                
            }               
        }
        System.out.println("Number of even nums: " + count);
        }
    }

Answer

I saw that you asked for a solution that started with your own code…

I know it’s faster but I assumed that we can find a solution using my code with some minor changes.

So I tried to understand what you were trying to do and I have not been able to decipher your method so starting from your macro I created a clearer version.


Changes

  • I used an ArrayList (list) as support instead of your array (even). The List is very convenient in your case because it has the contains() function and also its size is variable.
  • I took an even number in the array and looked for if there was at least one “half” of it.

Code

public static void main(String[] args) {
    Random random = new Random();

    int[] array = new int[20];
    ArrayList<Integer> list = new ArrayList<>();
    int evenNumber = 0;

    for (int i = 0; i < array.length; i++) {
        array[i] = random.nextInt(100);
    }

    System.out.println(Arrays.toString(array));

    for (int i = 0; i < array.length; i++) {
        // If I found an even number and this is NOT already in the list then I'll study it
        if (array[i] % 2 == 0 && !list.contains(array[i])) {
            evenNumber = array[i];
            for (int j = 0; j < array.length; j++) {
                // I add "evenNumber" to the list only if at least one its "half" exist in the array
                if (array[j] * 2 == evenNumber) {
                    list.add(evenNumber);
                    // I dont need to search more, I already found its "half"!
                    break;
                }
            }
        }
    }

    System.out.println("Doubled nums: " + list);
}

Sample output

[71, 88, 45, 97, 64, 31, 54, 12, 14, 86, 22, 42, 35, 44, 70, 65, 93, 85, 99, 14]
Doubled nums: [88, 44, 70]
Categories
discuss

How to capitalize one instance of a variable in a live template?

I am trying to make a template for React useState:

const [item, setItem] = useState('value')

const [$state$, set$state$] = useState($init$);$end$

Since item is the same, only with a capital I, is it possible to auto-capitalize the first letter?

I am doing it in VS Code like this:

const [$1, set${1/(.*)/${1:/capitalize}/}] = useState($2)

Answer

Create a second variable whose value depends on the first one.

For example, $state_ has its value initialized to capitalize(state) in the edit variables dialog

const [item, setItem] = useState('value')

const [$state$, set$state_$] = useState($init$);$end$

enter image description here

Categories
discuss

How to use consumer groups with Spring Data Redis for Redis Streams (keep getting NOGROUP)?

I’m trying to use Spring Data Redis to consume a Redis Stream using consumer groups, but keep getting the following exception:

Caused by: io.lettuce.core.RedisCommandExecutionException: NOGROUP No such key 'event-stream' or consumer group 'my-group' in XREADGROUP with GROUP option

The message seems to hint that I first need to create a consumer group? But the documentation does not provide any reference to this: https://github.com/spring-projects/spring-data-redis/blob/master/src/main/asciidoc/reference/redis-streams.adoc

Framework Versions:

  • Spring Boot 2.2.6
  • Lettuce 5.2.2
  • Redis 5.0.8

This is the code I’m using to consume the stream:

@Bean
@Autowired
public StreamMessageListenerContainer eventStreamPersistenceListenerContainerTwo(RedisConnectionFactory streamRedisConnectionFactory, RedisTemplate streamRedisTemplate) {

        StreamMessageListenerContainer.StreamMessageListenerContainerOptions<String, MapRecord<String, String, String>> containerOptions = StreamMessageListenerContainer.StreamMessageListenerContainerOptions
                        .builder().pollTimeout(Duration.ofMillis(100)).build();

        StreamMessageListenerContainer<String, MapRecord<String, String, String>> container = StreamMessageListenerContainer.create(streamRedisConnectionFactory,
                        containerOptions);

        container.receive(Consumer.from("my-group", "my-consumer"),
                        StreamOffset.create("event-stream", ReadOffset.latest()),
                        message -> {
                                System.out.println("MessageId: " + message.getId());
                                System.out.println("Stream: " + message.getStream());
                                System.out.println("Body: " + message.getValue());
                                streamRedisTemplate.opsForStream().acknowledge("my-group", message);
                        });

        /*Subscription subscription = container.receive(StreamOffset.fromStart("event-stream"), message -> {

                System.out.println("MessageId: " + message.getId());
                System.out.println("Stream: " + message.getStream());
                System.out.println("Body: " + message.getValue());
        });*/

        container.start();

        return container;
}

Full Stack Trace:

org.springframework.data.redis.RedisSystemException: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: NOGROUP No such key 'event-stream' or consumer group 'my-group' in XREADGROUP with GROUP option
    at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:54) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:52) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:41) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:44) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:42) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.lettuce.LettuceConnection.convertLettuceAccessException(LettuceConnection.java:270) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.lettuce.LettuceStreamCommands.convertLettuceAccessException(LettuceStreamCommands.java:471) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.lettuce.LettuceStreamCommands.xReadGroup(LettuceStreamCommands.java:361) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.connection.DefaultedRedisConnection.xReadGroup(DefaultedRedisConnection.java:529) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.DefaultStreamOperations$4.inRedis(DefaultStreamOperations.java:239) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.DefaultStreamOperations$RecordDeserializingRedisCallback.doInRedis(DefaultStreamOperations.java:305) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.DefaultStreamOperations$RecordDeserializingRedisCallback.doInRedis(DefaultStreamOperations.java:300) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:228) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:188) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:96) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.core.DefaultStreamOperations.read(DefaultStreamOperations.java:234) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.stream.DefaultStreamMessageListenerContainer.lambda$getReadFunction$3(DefaultStreamMessageListenerContainer.java:236) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.stream.StreamPollTask.doLoop(StreamPollTask.java:138) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.data.redis.stream.StreamPollTask.run(StreamPollTask.java:123) ~[spring-data-redis-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: io.lettuce.core.RedisCommandExecutionException: NOGROUP No such key 'event-stream' or consumer group 'my-group' in XREADGROUP with GROUP option
    at io.lettuce.core.ExceptionFactory.createExecutionException(ExceptionFactory.java:135) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.ExceptionFactory.createExecutionException(ExceptionFactory.java:108) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.AsyncCommand.completeResult(AsyncCommand.java:120) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.AsyncCommand.complete(AsyncCommand.java:111) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.CommandWrapper.complete(CommandWrapper.java:59) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.CommandHandler.complete(CommandHandler.java:654) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.CommandHandler.decode(CommandHandler.java:614) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.lettuce.core.protocol.CommandHandler.channelRead(CommandHandler.java:565) ~[lettuce-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.48.Final.jar:4.1.48.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.48.Final.jar:4.1.48.Final]
    ... 1 common frames omitted

Answer

Answering my own question. It seems as though you do need to explicitly create the stream and group first, even though not mentioned anywhere in the docs. Although there should really be a better way to initialize an empty stream other than publishing a message to it.

private void createConsumerGroup(String key, String group, RedisTemplate redisTemplate) {
        try {
                //redisTemplate.opsForStream().createGroup("my-stream", ReadOffset.from("0-0"), "my-group");
                redisTemplate.opsForStream().createGroup("event-stream", "my-group-2");
        } catch (RedisSystemException e) {
                if (e.getRootCause().getClass().equals(RedisBusyException.class)) {
                        log.info("STREAM - Redis group already exists, skipping Redis group creation: my-group-2");
                } else if (e.getRootCause().getClass().equals(RedisCommandExecutionException.class)) {
                        log.info("STREAM - Stream does not yet exist, creating empty stream: event-stream");
                        // TODO: There has to be a better way to create a stream than this!?
                        redisTemplate.opsForStream().add("event-stream", Collections.singletonMap("", ""));
                        redisTemplate.opsForStream().createGroup("event-stream", "my-group-2");
                } else throw e;
        }
}

EDIT: As mentioned by @anstue in the comments below, spring-data-redis 2.3.1+ now automatically creates the stream if it doesn’t exist, when calling createGroup. However, it will throw a RedisSystemBusyException if the group does already exist. So I’m updating the answer with the solution I am currently using, making sure to catch this exception.

public class EventStreamUtils {

    public static void createConsumerGroup(String key, String group, RedisTemplate redisTemplate) {
        try {
            // ReadOffset.from("0-0") will start reading stream from the very beginning.  Otherwise,
            // it will pick up at the point in the stream where the new group was created.
            //redisTemplate.opsForStream().createGroup(key, ReadOffset.from("0-0"), group);
            redisTemplate.opsForStream().createGroup(key, group);
        } catch (RedisSystemException e) {
            var cause = e.getRootCause();
            if (cause != null && RedisBusyException.class.equals(cause.getClass())) {
                log.info("STREAM - Redis group already exists, skipping Redis group creation: {}", group);
            } else throw e;
        }
    }
}
Categories
discuss

Modify Android App Bundle (aab) Contents before deploying

We have a build and release pipeline (Azure Devops) that deploys our APK Android app to various appcenter.ms environments. During the release process we unpack the apk, modify the contents with environment specific configuration, and then re-pack the apk.

Now that we are trying to do this with an Android App Bundle (AAB), we can no longer use apktool. How can we achieve the same thing with AAB that we could with APK?

This is a snippet of our working apk version of the script

## NOTE STUFF IS TRUNCATED!!! THIS IS NOT A COMPLETE SCRIPT!!! DO NOT COPY

brew list apktool &>/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install apktool
brew list xmlstarlet &>/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install xmlstarlet

# ... truncated ...

echo "Decompiling $zipPath"
apktool d $zipPath -o "apk"

cd apk

# ... truncated / modify androidmanifest.xml ...

unalignedPath="$apkPath.unaligned"
unsignedPath="$apkPath.unsigned"

cd ..

echo "Repackage apk to $unsignedPath"
apktool b apk -o $unsignedPath

echo "Sign"
jarsigner -keystore $keystorePath -storepass $keystorePass -keypass $keystorePass -verbose -sigalg MD5withRSA -digestalg SHA1 -signedjar $unalignedPath $unsignedPath $keyAlias
jarsigner -verify -verbose -certs $unalignedPath

echo "Zipalign"
$ANDROID_HOME/build-tools/27.0.3/zipalign -f -v 4 $unalignedPath $apkPath

When we simply change the file extension from apk to aab and run the same apktool, our folder structure is kind of messed up. folder structure when extracting apk from aab file

Also, the resources and manifest are already converted to protobuf, and I don’t think I can reverse engineer them.

Answer

To edit the manifest of the AAB, you’ll need to extract the file base/manifest/AndroidManifest.xml from the AAB, e.g.

unzip -p app.aab base/manifest/AndroidManifest.xml > AndroidManifest.pb

At this stage, in spite of its extension, the manifest is in a protocol buffer format (this is why I gave it the extension .pb above). You’ll thus then need to find a protocol buffer parser/editor to make the changes you need.

To parse the proto, you’ll need the definition of the protocol buffer, which you can find in this JAR: https://maven.google.com/com/android/tools/build/aapt2-proto/3.6.3-6040484/aapt2-proto-3.6.3-6040484.jar See message XmlNode in Resources.proto

Once you’ve made the changes on the parsed proto, re-serialize the proto and re-inject it at the same place with the same name in the AAB (it’s just a zip file).

Finally, you don’t need to zip-align the AAB, so remove this step.

Maybe in the future a tool will allow do you the conversion for you automatically, similarly to what apktool does. In the meantime, you can do it manually this way. Hope that helps.

Edit by Lionscribe

Simple step by step instructions.

  1. Extract the AndroidManifest.xml file from the AAB file as instructed above. For this use, keep the name as “AndroidManifest.xml“.
  2. Download protoc binary from https://developers.google.com/protocol-buffers/docs/downloads and extract binary to path or working folder.
  3. Download above referenced jar file, open jar with any zip program, and copy the files “Resources.proto” & “Configuration.proto” from the jar root folder to your working folder.
  4. Run command protoc --decode=aapt.pb.XmlNode Resources.proto < AndroidManifest.xml > output.txt to decode the file.
  5. Edit “output.txt” per your needs.
  6. Run protoc --encode=aapt.pb.XmlNode Resources.proto < output.txt > AndroidManifest_new.xml to encode the new version.
Categories
discuss

video call acceptance screen with Agora flutter

I’m trying to build a video calling app with Agora, I need to show acceptance screen like WhatsApp when user calling, if the app is exited i need to show calling screen when user is calling, I tried lot of thing but nothing works, I trying to do i flutter and but there is nothing much information on this,Please help me

Answer

First things first. You need to learn about some concepts before delving into your solution. Actually there isn’t an out of the box solution.

You need to use a couple of things together:

If you want a completely different thing and need to run some background process, there are bunch whole of things you should know first.
I suggest beginning here: https://flutter.dev/docs/development/packages-and-plugins/background-processes

Here is a usefull package to work with background processes that should be constantly running:

https://pub.dev/packages/background_fetch

Currently there are two packages which provides integration for agora.io:

I hope this can help you.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..