问:
Uncaught TypeError: Cannot read property 'chartInstance' of null
I tried to use the react-chartjs-2 library for the graphics part of my electron software. The problem is when I run via the npm start command, I get the following errors when I look in the console:

First error :

```<code>Uncaught Error: "arc" is not a registered element.
    at Registry._get (chart.js:5027)
    at Registry.getElement (chart.js:4974)
    at Chart.buildOrUpdateControllers (chart.js:5809)
    at Chart.update (chart.js:5843)
    at Chart.<anonymous> (chart.js:5602)
    at Chart._doResize (helpers.segment.js:601)
    at Chart._resize (chart.js:5691)
    at Chart.resize (chart.js:5662)
    at attached (chart.js:6233)
    at Chart.bindResponsiveEvents (chart.js:6245)
</code>```

Second error :

```<code>react-dom.development.js:88 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
</code>```

Third error :

```<code>Uncaught TypeError: Cannot read property 'chartInstance' of null
</code>```

I can't figure out where my error is coming from?

Here are the code :

App.js :

```<code>import React, { useState, useEffect, useRef, useSyncExternalStore } from 'react';
import Modal from './Modal/Modal'
import { Doughnut } from 'react-chartjs-2';
//JSON.parse(event.data)
//<Doughnut ref={chartReference} data={data} />

export default function App() {
  const chartReference=useRef(null);
  const [da,setDa]=useState({
    labels: ['Red','Green','Blue'],
    datasets: [
        {
            data: [5,7,6],
            backgroundColor: ['red','green','blue'],
        },
    ],
  });

  useEffect(() => {
    setInterval(() => {
      const chart = chartReference.current.chartInstance;
      setDa([
        Math.floor(Math.random() * 10) + 1,
        Math.floor(Math.random() * 10) + 1,
        Math.floor(Math.random() * 10) + 1,
      ]);
      chart.update();
    }, 2000);
  }, []);

  return (
        <div>
            <div className="home">
                <div className="template-1" id="temp1">
                    <div class="panel-5">
                        <div class="panel-header">
                            <h1>Profil des sections</h1>
                            <i class='bx bx-cog modal-trigger-panel'></i>
                        </div>
                        <div class="panel-body">
                            <div class="profil-container">
                                <Doughnut ref={chartReference} data={da} />
                            </div>
                            <div class="button-sec">
                                <input type="submit" value="Section 5" class="btn"/>
                                <input type="submit" value="Section 4" class="btn"/>
                                <input type="submit" value="Section 3" class="btn"/>
                                <input type="submit" value="Section 2" class="btn"/>
                                <input type="submit" value="Section 1" class="btn"/>
                            </div>
                            <div class="button-sail">
                                <input type="submit" value="Foresail" class="btn-hs modal-trigger-hs"/>
                                <input type="submit" value="Mainsail" class="btn-ms modal-trigger-ms"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
  );
}
</code>```

EDIT :

I added the following lines:

```<code>import {Chart,ArcElement} from 'chart.js';
Chart.register(ArcElement)
</code>```

It displays the graph but I get the following error in the console as the graph is not reloaded:

```<code>Uncaught TypeError: Cannot read property 'da' of undefined
    at App.js:35
</code>```

Regards,

Body:
I tried to use the react-chartjs-2 library for the graphics part of my electron software. The problem is when I run via the npm start command, I get the following errors when I look in the console:

First error :

Uncaught Error: "arc" is not a registered element.
    at Registry._get (chart.js:5027)
    at Registry.getElement (chart.js:4974)
    at Chart.buildOrUpdateControllers (chart.js:5809)
    at Chart.update (chart.js:5843)
    at Chart.<anonymous> (chart.js:5602)
    at Chart._doResize (helpers.segment.js:601)
    at Chart._resize (chart.js:5691)
    at Chart.resize (chart.js:5662)
    at attached (chart.js:6233)
    at Chart.bindResponsiveEvents (chart.js:6245)

Second error :

react-dom.development.js:88 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Third error :

Uncaught TypeError: Cannot read property 'chartInstance' of null

I can't figure out where my error is coming from?

Here are the code :

App.js :

import React, { useState, useEffect, useRef, useSyncExternalStore } from 'react';
import Modal from './Modal/Modal'
import { Doughnut } from 'react-chartjs-2';
//JSON.parse(event.data)
//<Doughnut ref={chartReference} data={data} />

export default function App() {
  const chartReference=useRef(null);
  const [da,setDa]=useState({
    labels: ['Red','Green','Blue'],
    datasets: [
        {
            data: [5,7,6],
            backgroundColor: ['red','green','blue'],
        },
    ],
  });

  useEffect(() => {
    setInterval(() => {
      const chart = chartReference.current.chartInstance;
      setDa([
        Math.floor(Math.random() * 10) + 1,
        Math.floor(Math.random() * 10) + 1,
        Math.floor(Math.random() * 10) + 1,
      ]);
      chart.update();
    }, 2000);
  }, []);

  return (

Profil des sections

                                <Doughnut ref={chartReference} data={da} />

                                <input type="submit" value="Section 5" class="btn"/>
                                <input type="submit" value="Section 4" class="btn"/>
                                <input type="submit" value="Section 3" class="btn"/>
                                <input type="submit" value="Section 2" class="btn"/>
                                <input type="submit" value="Section 1" class="btn"/>

                                <input type="submit" value="Foresail" class="btn-hs modal-trigger-hs"/>
                                <input type="submit" value="Mainsail" class="btn-ms modal-trigger-ms"/>

  );
}

EDIT :

I added the following lines:

import {Chart,ArcElement} from 'chart.js';
Chart.register(ArcElement)

It displays the graph but I get the following error in the console as the graph is not reloaded:

Uncaught TypeError: Cannot read property 'da' of undefined
    at App.js:35

Regards,


来源: stackexchange

问:
Android : Load a large file of 1.7GB as a MappedByteBufer
I need to load inside android a large file 1.7GB as a MappedByteBuffer at once and not as chunks.

I get OutOfMemory: Map failed error. Based on the docs there is a hard limit on the heap size allotted for each app.  I have tested it and the maximum is ~ 1.1GB ie I can load a dummy file as a MappedByteBuffer that is that long.

Nothing changes if I create an emulator with really large heap memory and RAM. Also no luck with setting largeHeap = true at manifest.

As this is a showcase and it is not going into production, I want to know if I can override this limit.

Anyone has an answer?

Code that I am using to load the file:

```<code>private fun loadModelFromInternalStorage(context: Context, modelName: String): MappedByteBuffer {
    val modelPath: String = context.filesDir.path + "/" + modelName
    val file = File(modelPath)
    val inputStream = FileInputStream(file)
    Log.v(TAG, file.length().toString())
    Log.v(TAG, Int.MAX_VALUE.toString())
    return inputStream.channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
}
</code>```

The limit of the MappedByteBuffer is Int.MAX_VALUE which is bigger that the file's length.

ContentLicense: CC BY-SA 4.0

Body:
I need to load inside android a large file 1.7GB as a MappedByteBuffer at once and not as chunks.

I get OutOfMemory: Map failed error. Based on the docs there is a hard limit on the heap size allotted for each app.  I have tested it and the maximum is ~ 1.1GB ie I can load a dummy file as a MappedByteBuffer that is that long.

Nothing changes if I create an emulator with really large heap memory and RAM. Also no luck with setting largeHeap = true at manifest.

As this is a showcase and it is not going into production, I want to know if I can override this limit.

Anyone has an answer?

Code that I am using to load the file:

private fun loadModelFromInternalStorage(context: Context, modelName: String): MappedByteBuffer {
    val modelPath: String = context.filesDir.path + "/" + modelName
    val file = File(modelPath)
    val inputStream = FileInputStream(file)
    Log.v(TAG, file.length().toString())
    Log.v(TAG, Int.MAX_VALUE.toString())
    return inputStream.channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
}

The limit of the MappedByteBuffer is Int.MAX_VALUE which is bigger that the file's length.


问:
Wanted to know if there is any way we can modify existing flux to receive messages at slower rate
Trying to modify kafka flux which is listening on a kafka topic to accept messages at slow rate. But the blow code is giving exception.

```<code>public class SampleConsumer {

    private static final Logger log = LoggerFactory.getLogger(SampleConsumer.class.getName());

    private static final String BOOTSTRAP_SERVERS = "localhost:9092";
    boolean slow = false;
    private static final String TOPIC = "demo-topic";

    private final ReceiverOptions<Integer, String> receiverOptions;
    private final DateTimeFormatter dateFormat;

    public SampleConsumer(String bootstrapServers) {

        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.CLIENT_ID_CONFIG, "sample-consumer");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "sample-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        receiverOptions = ReceiverOptions.create(props);
        dateFormat = DateTimeFormatter.ofPattern("HH:mm:ss:SSS z dd MMM yyyy");
    }

    public void consumeMessages(String topic, CountDownLatch latch) {

        ReceiverOptions<Integer, String> options = receiverOptions.subscription(Collections.singleton(topic))
                .addAssignListener(partitions -> log.debug("onPartitionsAssigned {}", partitions))
                .addRevokeListener(partitions -> log.debug("onPartitionsRevoked {}", partitions));
        Flux<ReceiverRecord<Integer, String>> kafkaFlux = KafkaReceiver.create(options).receive();

        Disposable disposable = kafkaFlux.doOnNext(record -> System.out.println("Received message: value="+
                record.value()) )
        .subscribe(record -> {
            ReceiverOffset offset = record.receiverOffset();
            offset.acknowledge();

        });

        if(slow) // logic has been implemented for this
{
            disposable.dispose();

            disposable = kafkaFlux.take(1, true).doOnNext(record -> System.out.println("Received slow message: value="+
                    record.value()) )
            .subscribe(record -> {
                ReceiverOffset offset = record.receiverOffset();
                offset.acknowledge();

            });
        }

    }}
</code>```

Exception:
Caused by reactor.core.Exceptions$StaticRejectedExecutionException : Scheduler unavailable

Wanted to know if there is any way we can modify existing flux to receive messages at slower rate

Body:
Trying to modify kafka flux which is listening on a kafka topic to accept messages at slow rate. But the blow code is giving exception.

public class SampleConsumer {

    private static final Logger log = LoggerFactory.getLogger(SampleConsumer.class.getName());

    private static final String BOOTSTRAP_SERVERS = "localhost:9092";
    boolean slow = false;
    private static final String TOPIC = "demo-topic";

    private final ReceiverOptions<Integer, String> receiverOptions;
    private final DateTimeFormatter dateFormat;

    public SampleConsumer(String bootstrapServers) {

        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.CLIENT_ID_CONFIG, "sample-consumer");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "sample-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        receiverOptions = ReceiverOptions.create(props);
        dateFormat = DateTimeFormatter.ofPattern("HH:mm:ss:SSS z dd MMM yyyy");
    }

    public void consumeMessages(String topic, CountDownLatch latch) {

        ReceiverOptions<Integer, String> options = receiverOptions.subscription(Collections.singleton(topic))
                .addAssignListener(partitions -> log.debug("onPartitionsAssigned {}", partitions))
                .addRevokeListener(partitions -> log.debug("onPartitionsRevoked {}", partitions));
        Flux<ReceiverRecord<Integer, String>> kafkaFlux = KafkaReceiver.create(options).receive();

        Disposable disposable = kafkaFlux.doOnNext(record -> System.out.println("Received message: value="+
                record.value()) )
        .subscribe(record -> {
            ReceiverOffset offset = record.receiverOffset();
            offset.acknowledge();

        });

        if(slow) // logic has been implemented for this
{
            disposable.dispose();

            disposable = kafkaFlux.take(1, true).doOnNext(record -> System.out.println("Received slow message: value="+
                    record.value()) )
            .subscribe(record -> {
                ReceiverOffset offset = record.receiverOffset();
                offset.acknowledge();

            });
        }

    }}

Exception:
Caused by reactor.core.Exceptions$StaticRejectedExecutionException : Scheduler unavailable

Wanted to know if there is any way we can modify existing flux to receive messages at slower rate


问:
Flex items not covering the whole width
I am styling a container which is in another container and I want to use the display:flex and set it to space between. But when I do that it not working, the list items are only covering that width of the content. How best can I set the list to cover the whole width?

I tried to change the display to inline-block and it still not working

Title: Flex items not covering the whole width


问:
MAGMA: RelativeField(K,E) where K and E are isomorphic
Consider the following MAGMA-Code:

```<code>R<x> := PolynomialRing(Rationals());
F := NumberField(x^2 + 1);
E := ext<F | x^2 - 2>;
f := DefiningPolynomial(AbsoluteField(E));
K := NumberField(f);
a := Roots(f, E)[1][1];
Embed(K, E, a);
IsSubfield(K, E);
M := RelativeField(K, E);
BaseField(M);
</code>```

Executed with the MAGMA calculator Running Magma V2.27-7. Seed: 3598054538

The MAGMA Manual defines the Function RelativeField(F, L) as "Given number fields L and F such that Magma knows that F is a subfield of L, return an isomorphic number field M defined as an extension over F."
Since IsSubfield(K, E) above return true, Magma certainly knows that K is a subfield of E.
Why is M defined over the Rationals and not over K? How can I actually get M defined over K?

Note: Changing the definition of f to (e.g.) x^2 - 2 or x-1 yields the results I would expect.
Something behaves differently when K and E are Isomorphic.

Body:
Consider the following MAGMA-Code:

R<x> := PolynomialRing(Rationals());
F := NumberField(x^2 + 1);
E := ext<F | x^2 - 2>;
f := DefiningPolynomial(AbsoluteField(E));
K := NumberField(f);
a := Roots(f, E)[1][1];
Embed(K, E, a);
IsSubfield(K, E);
M := RelativeField(K, E);
BaseField(M);

Executed with the MAGMA calculator Running Magma V2.27-7. Seed: 3598054538

The MAGMA Manual defines the Function RelativeField(F, L) as "Given number fields L and F such that Magma knows that F is a subfield of L, return an isomorphic number field M defined as an extension over F."
Since IsSubfield(K, E) above return true, Magma certainly knows that K is a subfield of E.
Why is M defined over the Rationals and not over K? How can I actually get M defined over K?

Note: Changing the definition of f to (e.g.) x^2 - 2 or x-1 yields the results I would expect.
Something behaves differently when K and E are Isomorphic.


问:
How do you draw boxes from point A to point B when condition is met (candle closes above certain highs/lows)?
I am trying to figure out on how to draw boxes from 2 recent points after a candle closes above/below prior "protected highs/lows".

Example,

Point A = close > high[1]
Point B = close < low[1]

Range is defined when both Point A and Point B is formed (minimum 2 candles)

When price increase and breaks structure of the Range, I'll draw a box from the previous highest high after Point A to the lowest low after Point B before the structural range was broken.

When this happens,  the lowest low after Point B becomes my protected low. A protected high is only formed once Point B forms (which also creates the above defined Range.

The process will repeat itself depending whether there are candle closes above protected highs or protected lows.

On a bearish scenario, the box will be drawn from lowest low after Point B to the highest high after Point A. (a reverse)

I won't need to use var keyword as I am okay if multiple boxes are created. Any help would be much appreciated as I get a little confused with the loops in the codes.

Point A is Red Dot and Point B is Green dots in the below image

Example

Got stuck defining the loops where protected highs and lows are defined and how they are created again when candles are closed above/below prior ones.


问:
kotlin dagger "'<any>' could not be resolved"
I have working java code

```<code>public class ItemCallback<T extends Identifiable<?>> extends DiffUtil.ItemCallback<T> {

    @Inject
    public ItemCallback() {}

    @Override
    public boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem) {
        return oldItem.getId().equals(newItem.getId());
    }

    @Override
    public boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem) {
        return oldItem.compareContent(newItem);
    }
}
</code>```

and i wrote correspond kotlin code

```<code>class ItemCallback<T : ListElementModel<*>> @Inject constructor() : DiffUtil.ItemCallback<T>() {

    override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem == newItem
    }
}
</code>```

and caught error
"error: InjectProcessingStep was unable to process 'ItemCallback()' because 'any' could not be resolved."

I understand that the error in star-projections. But I don't know how to solve it.

Body:
I have working java code

public class ItemCallback<T extends Identifiable<?>> extends DiffUtil.ItemCallback<T> {

    @Inject
    public ItemCallback() {}

    @Override
    public boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem) {
        return oldItem.getId().equals(newItem.getId());
    }

    @Override
    public boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem) {
        return oldItem.compareContent(newItem);
    }
}

and i wrote correspond kotlin code

class ItemCallback<T : ListElementModel<*>> @Inject constructor() : DiffUtil.ItemCallback<T>() {

    override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem == newItem
    }
}

and caught error
"error: InjectProcessingStep was unable to process 'ItemCallback()' because 'any' could not be resolved."

I understand that the error in star-projections. But I don't know how to solve it.


问:
Pushing large docker image to private registry is endless with multiple retryings
Suddenly we got a problem while pushing to our private registry a large docker image.

```<code>b09ec9b220b5: Pushing [=======================>                           ]  1.871GB/3.905GB // always interrupted when reached around 2.3GB/3.905GB
935138875f7e: Layer already exists
844a98711e4c: Layer already exists
f11fbff78593: Layer already exists
cfe955540946: Layer already exists
0e9af88280bb: Layer already exists
08de5656e13a: Layer already exists
5f70bf18a086: Layer already exists
03825ee9b44a: Layer already exists
407fdf993b55: Layer already exists
315572e6ad81: Layer already exists
44dda8402940: Layer already exists
25972ffba58c: Layer already exists
dc6462f7bb8b: Layer already exists
a4db1a405763: Layer already exists
9f4f964da727: Layer already exists
49b333f7bad4: Layer already exists
a463dbda4664: Layer already exists
a9099c3159f5: Layer already exists
</code>```

Traefik and registry run in docker swarm:

Traefik docker .yml file

```<code>version: '3.6'

services:
  traefik:
    image: traefik:2.9.6
    command:
      # - '--log.level=DEBUG'
      - '--api=true'
      - '--api.dashboard=true'
      - '--providers.docker.endpoint=unix:///var/run/docker.sock'
      - '--providers.docker.swarmMode=true'
      - '--providers.docker.exposedbydefault=false'
      - '--providers.docker.network=traefik-proxy'
      - '--entrypoints.web.address=:80'
      - '--entrypoints.websecure.address=:443'
      - '--certificatesresolvers.letsencryptresolver.acme.httpchallenge=true'
      - '--certificatesresolvers.letsencryptresolver.acme.httpchallenge.entrypoint=web'
      - '--certificatesresolvers.letsencryptresolver.acme.email=developer@domain.com'
      - '--certificatesresolvers.letsencryptresolver.acme.storage=/letsencrypt/acme.json'
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - acme-certs:/letsencrypt
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - traefik-proxy
    deploy:
      placement:
        constraints:
          - node.role == manager
      labels:
        - 'traefik.enable=true'
        # HTTP Catchall for redirecting HTTP -> HTTPS
        - 'traefik.http.routers.http-catchall.rule=PathPrefix(`/`)'
        - 'traefik.http.routers.http-catchall.entrypoints=web'
        - 'traefik.http.routers.http-catchall.middlewares=redirect-to-https'
        - 'traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https'
        # Traefik dashboard
        - 'traefik.http.routers.traefik.rule=Host(`traefik.domain.com`)'
        - 'traefik.http.routers.traefik.entrypoints=websecure'
        - 'traefik.http.routers.traefik.tls.certresolver=letsencryptresolver'
        - 'traefik.http.routers.traefik.service=api@internal'
        - 'traefik.http.services.api@internal.loadbalancer.server.port=8080'
        - 'traefik.http.routers.traefik.middlewares=traefik-auth'
        - 'traefik.http.middlewares.traefik-auth.basicauth.users=admin:$$2y$$10$$OwPg6oWN2iJk5Syde7yIt.tKebbZwtQkaPQ.0AaaaFjNIb1h8bJ6a'
      resources:
        limits:
          memory: "512M"

volumes:
  acme-certs:

networks:
  traefik-proxy:
    external: true
</code>```

Registry docker .yml file

```<code>version: '3.4'

services:
  registry:
    image: registry:2.8.1
    ports:
      - "5000:5000"
    environment:
      - REGISTRY_AUTH=htpasswd
      - REGISTRY_STORAGE_DELETE_ENABLED=true
      - REGISTRY_AUTH_HTPASSWD_PATH=/httpasswd_storage/htpasswd
      - REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm
    volumes:
      - ./htpasswd_backup:/httpasswd_storage
      - registry-data:/var/lib/registry
    networks:
      - traefik-proxy
      - registry-ui-net
    deploy:
      labels:
        - 'traefik.enable=true'
        - 'traefik.docker.network=traefik-proxy'
        - "traefik.http.routers.registry.rule=Host(`registry1.domain.com`)"
        - 'traefik.http.routers.registry.entrypoints=websecure'
        - 'traefik.http.routers.registry.tls.certresolver=letsencryptresolver'
        - 'traefik.http.services.registry.loadbalancer.server.port=5000'

networks:
  traefik-proxy:
    external: true
  registry-ui-net:

volumes:
  registry-data:
</code>```

There is no any errors in docker registry container logs. When I push this image from my local MacOS - it is endless but if it is pushed from Jenkins (which is on the same server with registry) - there are around 5 retries and then 500 error

Body:
Suddenly we got a problem while pushing to our private registry a large docker image.

b09ec9b220b5: Pushing [=======================>                           ]  1.871GB/3.905GB // always interrupted when reached around 2.3GB/3.905GB
935138875f7e: Layer already exists
844a98711e4c: Layer already exists
f11fbff78593: Layer already exists
cfe955540946: Layer already exists
0e9af88280bb: Layer already exists
08de5656e13a: Layer already exists
5f70bf18a086: Layer already exists
03825ee9b44a: Layer already exists
407fdf993b55: Layer already exists
315572e6ad81: Layer already exists
44dda8402940: Layer already exists
25972ffba58c: Layer already exists
dc6462f7bb8b: Layer already exists
a4db1a405763: Layer already exists
9f4f964da727: Layer already exists
49b333f7bad4: Layer already exists
a463dbda4664: Layer already exists
a9099c3159f5: Layer already exists

Traefik and registry run in docker swarm:

Traefik docker .yml file

version: '3.6'

services:
  traefik:
    image: traefik:2.9.6
    command:
      # - '--log.level=DEBUG'
      - '--api=true'
      - '--api.dashboard=true'
      - '--providers.docker.endpoint=unix:///var/run/docker.sock'
      - '--providers.docker.swarmMode=true'
      - '--providers.docker.exposedbydefault=false'
      - '--providers.docker.network=traefik-proxy'
      - '--entrypoints.web.address=:80'
      - '--entrypoints.websecure.address=:443'
      - '--certificatesresolvers.letsencryptresolver.acme.httpchallenge=true'
      - '--certificatesresolvers.letsencryptresolver.acme.httpchallenge.entrypoint=web'
      - '--certificatesresolvers.letsencryptresolver.acme.email=developer@domain.com'
      - '--certificatesresolvers.letsencryptresolver.acme.storage=/letsencrypt/acme.json'
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - acme-certs:/letsencrypt
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - traefik-proxy
    deploy:
      placement:
        constraints:
          - node.role == manager
      labels:
        - 'traefik.enable=true'
        # HTTP Catchall for redirecting HTTP -> HTTPS
        - 'traefik.http.routers.http-catchall.rule=PathPrefix(`/`)'
        - 'traefik.http.routers.http-catchall.entrypoints=web'
        - 'traefik.http.routers.http-catchall.middlewares=redirect-to-https'
        - 'traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https'
        # Traefik dashboard
        - 'traefik.http.routers.traefik.rule=Host(`traefik.domain.com`)'
        - 'traefik.http.routers.traefik.entrypoints=websecure'
        - 'traefik.http.routers.traefik.tls.certresolver=letsencryptresolver'
        - 'traefik.http.routers.traefik.service=api@internal'
        - 'traefik.http.services.api@internal.loadbalancer.server.port=8080'
        - 'traefik.http.routers.traefik.middlewares=traefik-auth'
        - 'traefik.http.middlewares.traefik-auth.basicauth.users=admin:$$2y$$10$$OwPg6oWN2iJk5Syde7yIt.tKebbZwtQkaPQ.0AaaaFjNIb1h8bJ6a'
      resources:
        limits:
          memory: "512M"

volumes:
  acme-certs:

networks:
  traefik-proxy:
    external: true

Registry docker .yml file

version: '3.4'

services:
  registry:
    image: registry:2.8.1
    ports:
      - "5000:5000"
    environment:
      - REGISTRY_AUTH=htpasswd
      - REGISTRY_STORAGE_DELETE_ENABLED=true
      - REGISTRY_AUTH_HTPASSWD_PATH=/httpasswd_storage/htpasswd
      - REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm
    volumes:
      - ./htpasswd_backup:/httpasswd_storage
      - registry-data:/var/lib/registry
    networks:
      - traefik-proxy
      - registry-ui-net
    deploy:
      labels:
        - 'traefik.enable=true'
        - 'traefik.docker.network=traefik-proxy'
        - "traefik.http.routers.registry.rule=Host(`registry1.domain.com`)"
        - 'traefik.http.routers.registry.entrypoints=websecure'
        - 'traefik.http.routers.registry.tls.certresolver=letsencryptresolver'
        - 'traefik.http.services.registry.loadbalancer.server.port=5000'

networks:
  traefik-proxy:
    external: true
  registry-ui-net:

volumes:
  registry-data:

There is no any errors in docker registry container logs. When I push this image from my local MacOS - it is endless but if it is pushed from Jenkins (which is on the same server with registry) - there are around 5 retries and then 500 error


问:
How to use @ModelAttribute to map nested pojo class from javascript form-data
This is RestController,

In this, i was trying to map data coming from javascript to ContactDetaislDto class

```<code>@RestController
public class ContactDetailsRestController {

    @PostMapping("/save/contact/details")
    public ContactDetailsDto saveContactDetails(@ModelAttribute ContactDetailsDto contactDetailsDto,
            Principal principal) {

        System.out.println(contactDetailsDto);

        return contactDetailsDto;
    }
}
</code>```

ContactDetailsDto.java class

In this which have list of phone number class

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
public class ContactDetailsDto {

    //Remaining other fields

    @NotBlank
    private List<PhoneNumber> phoneNos = new ArrayList<>();

}
</code>```

PhoneNumber class

In this , just one more parametrized constructor  which take string phoneNo

```<code>@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PhoneNumber {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false, length = 10)
    private String phoneNo;

    // Mapping
    @ManyToOne
    @JoinColumn(name = "contact_detail_id", nullable = false)
    private ContactDetails contactDetails;

    @Override
    public String toString() {
        return "PhoneNumber [id=" + id + ", phoneNo=" + phoneNo + "]";
    }

    public PhoneNumber(String phoneNo) {
        super();
        this.phoneNo = phoneNo;
    }

}
</code>```

From javascript sending data in formdata

```<code>let fdata = new FormData();
    //some
    fdata.append("phoneNos", "1234");
    fdata.append("phoneNos", "4567");
    fdata.append("phoneNos", "8971");

    fetch("/save/contact/details", {
        body: fdata,
        method: "post"
        }).then((response) => {
            if (response.ok) {
                //Some code
            } else {
                //Some code
            }
        });
</code>```

And error is

[2m2023-01-13 19:51:20.859[0;39m [33m WARN[0;39m [35m7176[0;39m
[2m---[0;39m [2m[nio-8080-exec-3][0;39m
[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved
[org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1
errorsField error in object 'contactDetailsDto' on field
'phoneNos': rejected value [asd,awsd,wew]; codes
[typeMismatch.contactDetailsDto.phoneNos,typeMismatch.phoneNos,typeMismatch.java.util.List,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [contactDetailsDto.phoneNos,phoneNos]; arguments []; default
message [phoneNos]]; default message [Failed to convert property value
of type 'java.lang.String[]' to required type 'java.util.List' for
property 'phoneNos'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type [java.lang.Integer] for
value 'asd'; nested exception is java.lang.NumberFormatException: For
input string: "asd"]]

Not able to understand why it converting string to int

and how can I map using @ModelAttribute with nested pojo class

I have creating simple project with similar class and that works perfectly.

Body:
This is RestController,

In this, i was trying to map data coming from javascript to ContactDetaislDto class

@RestController
public class ContactDetailsRestController {

    @PostMapping("/save/contact/details")
    public ContactDetailsDto saveContactDetails(@ModelAttribute ContactDetailsDto contactDetailsDto,
            Principal principal) {

        System.out.println(contactDetailsDto);

        return contactDetailsDto;
    }
}

ContactDetailsDto.java class

In this which have list of phone number class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ContactDetailsDto {

    //Remaining other fields

    @NotBlank
    private List<PhoneNumber> phoneNos = new ArrayList<>();

}

PhoneNumber class

In this , just one more parametrized constructor  which take string phoneNo

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PhoneNumber {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false, length = 10)
    private String phoneNo;

    // Mapping
    @ManyToOne
    @JoinColumn(name = "contact_detail_id", nullable = false)
    private ContactDetails contactDetails;

    @Override
    public String toString() {
        return "PhoneNumber [id=" + id + ", phoneNo=" + phoneNo + "]";
    }

    public PhoneNumber(String phoneNo) {
        super();
        this.phoneNo = phoneNo;
    }

}

From javascript sending data in formdata

let fdata = new FormData();
    //some
    fdata.append("phoneNos", "1234");
    fdata.append("phoneNos", "4567");
    fdata.append("phoneNos", "8971");

    fetch("/save/contact/details", {
        body: fdata,
        method: "post"
        }).then((response) => {
            if (response.ok) {
                //Some code
            } else {
                //Some code
            }
        });

And error is

[2m2023-01-13 19:51:20.859[0;39m [33m WARN[0;39m [35m7176[0;39m
[2m---[0;39m [2m[nio-8080-exec-3][0;39m
[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved
[org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1
errorsField error in object 'contactDetailsDto' on field
'phoneNos': rejected value [asd,awsd,wew]; codes
[typeMismatch.contactDetailsDto.phoneNos,typeMismatch.phoneNos,typeMismatch.java.util.List,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [contactDetailsDto.phoneNos,phoneNos]; arguments []; default
message [phoneNos]]; default message [Failed to convert property value
of type 'java.lang.String[]' to required type 'java.util.List' for
property 'phoneNos'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type [java.lang.Integer] for
value 'asd'; nested exception is java.lang.NumberFormatException: For
input string: "asd"]]

Not able to understand why it converting string to int

and how can I map using @ModelAttribute with nested pojo class

I have creating simple project with similar class and that works perfectly.


问:
Heroku Backend/Server uses URL twice
We have some issues on our MERN-App while we want to built our Website on Heroku.
In the past it worked very well but after a change of my hard disk I've downloaded the git again but now heroku can't find the path of my index file.

We think that the issue happens in our server index. Please see the attached code:

Version 1

```<code>app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, '/../client/build/index.html'));
  });
</code>```

Were we get the following error:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'

and Version2

```<code>app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client/build/index.html'));
  });
</code>```

Were we get the following error:
Error: ENOENT: no such file or directory, stat '/app/server/client/build/index.html'

Our file structure is:
-client
--build
---index.html
-server
-index.js

When i inspect in the browser the requested backend call the URL is like:
Request URL: https://xxxx.herokuapp.com/www.XXXX.de/request/requestTERM

And our package json looks like

```<code>"build": "cd client && npm run build",
"install-client": "cd client && npm install",
"heroku-postbuild": "npm run install-client && npm run build"
</code>```

We have no idea to fix this issue and will probably find some help over here.

Thank you in advance

Title: Heroku Backend/Server uses URL twice

Body:
We have some issues on our MERN-App while we want to built our Website on Heroku.
In the past it worked very well but after a change of my hard disk I've downloaded the git again but now heroku can't find the path of my index file.

We think that the issue happens in our server index. Please see the attached code:

Version 1

app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, '/../client/build/index.html'));
  });

Were we get the following error:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'

and Version2

app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client/build/index.html'));
  });

Were we get the following error:
Error: ENOENT: no such file or directory, stat '/app/server/client/build/index.html'

Our file structure is:
-client
--build
---index.html
-server
-index.js

When i inspect in the browser the requested backend call the URL is like:
Request URL: https://xxxx.herokuapp.com/www.XXXX.de/request/requestTERM

And our package json looks like

"build": "cd client && npm run build",
"install-client": "cd client && npm install",
"heroku-postbuild": "npm run install-client && npm run build"

We have no idea to fix this issue and will probably find some help over here.

Thank you in advance


问:
Ionic/angular nested rotuer outlet only works on initial load
I have multiple featured modules/section in my angular/ionic app. I have created a few routing sections that use lazy loading for the children. The app and the child routing works 100% on load but if I navigate away from the page and then come back the nested router outlet stops working.

I have tried setting the outlet in the route - failed

I have tried setting the parent to not being an empty path - failed

I have tried navigating using the relative setup but that only works once on page load - failed

Below is the the router code to navigate the children

```<code>this.router.navigate([`${filterName.toLowerCase()}`,], {relativeTo: this.route} );
</code>```

Below is the routing for this feature module

```<code>const routes: Routes = [
    {
        path: ":projectId",
        component: ProjectDetailsPage,
        children: [
            {
                path: "about",
                loadChildren: () =>
                    import("./pages/about/about.module").then(
                        (m) => m.AboutPageModule
                    ),
            },
            {
                path: "faqs",
                loadChildren: () =>
                    import("./pages/faqs/faqs.module").then(
                        (m) => m.FaqsPageModule
                    ),
            },
            {
                path: "activity",
                loadChildren: () =>
                    import("./pages/activity/activity.module").then(
                        (m) => m.ActivityPageModule
                    ),
            },
            {
                path: "metrics",
                loadChildren: () =>
                    import("./pages/metrics/metrics.module").then(
                        (m) => m.MetricsPageModule
                    ),
            },
            {
                path: "trade",
                loadChildren: () =>
                    import("./pages/trade/trade.module").then(
                        (m) => m.TradePageModule
                    ),
            },
            {
                path: "buy",
                loadChildren: () =>
                    import("./pages/buy/buy.module").then(
                        (m) => m.BuyPageModule
                    ),
            },
        ],
    },
];
</code>```

Body:
I have multiple featured modules/section in my angular/ionic app. I have created a few routing sections that use lazy loading for the children. The app and the child routing works 100% on load but if I navigate away from the page and then come back the nested router outlet stops working.

I have tried setting the outlet in the route - failed

I have tried setting the parent to not being an empty path - failed

I have tried navigating using the relative setup but that only works once on page load - failed

Below is the the router code to navigate the children

this.router.navigate([`${filterName.toLowerCase()}`,], {relativeTo: this.route} );

Below is the routing for this feature module

const routes: Routes = [
    {
        path: ":projectId",
        component: ProjectDetailsPage,
        children: [
            {
                path: "about",
                loadChildren: () =>
                    import("./pages/about/about.module").then(
                        (m) => m.AboutPageModule
                    ),
            },
            {
                path: "faqs",
                loadChildren: () =>
                    import("./pages/faqs/faqs.module").then(
                        (m) => m.FaqsPageModule
                    ),
            },
            {
                path: "activity",
                loadChildren: () =>
                    import("./pages/activity/activity.module").then(
                        (m) => m.ActivityPageModule
                    ),
            },
            {
                path: "metrics",
                loadChildren: () =>
                    import("./pages/metrics/metrics.module").then(
                        (m) => m.MetricsPageModule
                    ),
            },
            {
                path: "trade",
                loadChildren: () =>
                    import("./pages/trade/trade.module").then(
                        (m) => m.TradePageModule
                    ),
            },
            {
                path: "buy",
                loadChildren: () =>
                    import("./pages/buy/buy.module").then(
                        (m) => m.BuyPageModule
                    ),
            },
        ],
    },
];


问:
Forward different subdomain requests to different localhost ports in NET Core
I want to forward different subdomain requests to different localhost ports in NET Core.

How Can I achieve this?

Seems like net core middleware or reverse proxy like yarp is not supporting this.


问:
python plotly - produce plot upon two clicks
Let's suppose I have a plotly graph_objects.Figure object containing a scatterplot:

```<code>y = np.random.rand(10)
x = np.random.rand(10)
names = ['A', 'B', 'C', 'D', 'E',
        'F', 'G', 'H', 'I', 'L']
fig = go.FigureWidget()
fig.add_trace(go.Scatter(
                x=x,
                y=y,
                name='Base scatter',
                mode='markers',
                marker=dict(size=7),
                customdata = names,
                hovertemplate= '<b>x:</b> %{x}<br><b>y:</b> %{y}<br><b>Name:</b> %{customdata}<br>'))

fig.update_layout(title='Test')
fig.show()
</code>```

Which produces the following image:

I would like that upon click on two different points, a new temporary plot appears with information about the two points (e.g. those two points in another canvas connected by a line).

I've looked into click handlers but I can't figure out how to make it work.

Thanks

Body:
Let's suppose I have a plotly graph_objects.Figure object containing a scatterplot:

y = np.random.rand(10)
x = np.random.rand(10)
names = ['A', 'B', 'C', 'D', 'E',
        'F', 'G', 'H', 'I', 'L']
fig = go.FigureWidget()
fig.add_trace(go.Scatter(
                x=x,
                y=y,
                name='Base scatter',
                mode='markers',
                marker=dict(size=7),
                customdata = names,
                hovertemplate= 'x: %{x}
y: %{y}
Name: %{customdata}
'))

fig.update_layout(title='Test')
fig.show()

Which produces the following image:

I would like that upon click on two different points, a new temporary plot appears with information about the two points (e.g. those two points in another canvas connected by a line).

I've looked into click handlers but I can't figure out how to make it work.

Thanks


问:
Django html template in production
im not sure if that is normal in django production deployment but im using django on a ubuntu and using nginx and gunicorn but im still able when i go to network tab to see all the html and javascript code . i have debug mode False and followed different tutorials but none shows or explain the expected behavior , like is it normal to see all the static files in the source and network and the code within those files ?</p>

Title: Django html template in production


问:
How to interact with Polkadot network using .Net
I need to interact with Polkadot network using .Net. More specifically, I need to estimate a transaction fee for simple DOT transfer transactions.

I found only one .Net wrapper for Polkadot api https://github.com/usetech-llc/polkadot_api_dotnet
But It seems that the repository is no longer supported.

Could anyone help me? Thank you in advance!


问:
Styles not getting applied when I upgrade to Material UI 5 for elements
I recently upgraded my Material UI from V4 to 5 and stuck with a truckload of issues. One of them is that the styles are messing up when i move away from JSS

The arrow icon need to get the styles and the styles are not getting applied.

```<code>const StyledPopper = styled(Popper)(({ theme }) => {
  return {
    [`&.${classes.popper}`]: {
      top: "100px !important",
      left: "200px !important",
      zIndex: 1,
      '&[x-placement*="bottom"] $arrow': {
        // is not getting applied
        marginTop: theme.spacing(-5.25),
        "&::before": {
          borderWidth: "0 1em 1em 1em",
          borderColor: `transparent transparent red transparent`
        }
      }
    },
    [`& .${classes.arrow}`]: {
      position: "absolute",
      "&::before": {
        content: '""',
        display: "block",
        borderStyle: "solid"
      }
    }
  };
});

<StyledPopper
        open
        placement="bottom-end"
        anchorEl={
          document && document.getElementById("location-confirmer-desktop")
        }
        modifiers={{ arrow: { enabled: true, element: arrowRef } }}
        className={classes.popper}
      >
        <Box ref={setArrowRef} className={classes.arrow} />
        <Box>This is the content</Box>
      </StyledPopper>
</code>```

https://codesandbox.io/s/combobox-demo-material-ui-forked-v5-8-4-g0pyhg?file=/demo.tsx

Body:
I recently upgraded my Material UI from V4 to 5 and stuck with a truckload of issues. One of them is that the styles are messing up when i move away from JSS

The arrow icon need to get the styles and the styles are not getting applied.

const StyledPopper = styled(Popper)(({ theme }) => {
  return {
    [`&.${classes.popper}`]: {
      top: "100px !important",
      left: "200px !important",
      zIndex: 1,
      '&[x-placement*="bottom"] $arrow': {
        // is not getting applied
        marginTop: theme.spacing(-5.25),
        "&::before": {
          borderWidth: "0 1em 1em 1em",
          borderColor: `transparent transparent red transparent`
        }
      }
    },
    [`& .${classes.arrow}`]: {
      position: "absolute",
      "&::before": {
        content: '""',
        display: "block",
        borderStyle: "solid"
      }
    }
  };
});

https://codesandbox.io/s/combobox-demo-material-ui-forked-v5-8-4-g0pyhg?file=/demo.tsx


问:
Cannot use import statement outside a module (using react testing library)
During developing vite react project I got a problem with react testing library or jest.
I try to test async user fetching function, but jest is throwing an error

"Jest encountered an unexpected token"

&&

"Cannot use import statement outside a module".

As it shows, the problem is in axios import. Here is a photo of error and an example of code:

Here is User component:

```<code>import axios from "axios";
import React, { useEffect, useState } from "react";

const Users = () => {
  const [users, setUsers] = useState([]);
  const fetchUsers = async () => {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );
    setUsers(response.data);
  };
  useEffect(() => {
    fetchUsers();
  }, []);
  return (
    <ul>
      {users.map((user) => (
        <li data-testid="user-item" key={user.id}> {user.name}</li>
      ))}
    </ul>
  );
};

export default Users;
</code>```

Here is test file:

```<code>import {  render, screen } from "@testing-library/react";
import axios from "axios";

import Users from "./Users";

jest.mock('axios');
describe("users", () => {
  let response;
  beforeEach(() => {
    response = {
      data: [
        {
          id: 1,
          name: "Leanne Graham",
        },
        {
          id: 2,
          name: "Ervin Howell",
        },
        {
          id: 3,
          name: "Clementine Bauch",
        },
      ],
    };
  });

  test("fetching users", async () => {
    axios.get.mockReturnValue(response);
    render(<Users/>)
    const users = await screen.findAllByTestId('user-item');
    expect(users.length).toBe(3)
  });
});

</code>```

I have no idea what to do (((

Body:
During developing vite react project I got a problem with react testing library or jest.
I try to test async user fetching function, but jest is throwing an error

"Jest encountered an unexpected token"

&&

"Cannot use import statement outside a module".

As it shows, the problem is in axios import. Here is a photo of error and an example of code:

Here is User component:

import axios from "axios";
import React, { useEffect, useState } from "react";

const Users = () => {
  const [users, setUsers] = useState([]);
  const fetchUsers = async () => {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );
    setUsers(response.data);
  };
  useEffect(() => {
    fetchUsers();
  }, []);
  return (

      {users.map((user) => (

 {user.name}

      ))}

  );
};

export default Users;

Here is test file:

import {  render, screen } from "@testing-library/react";
import axios from "axios";

import Users from "./Users";

jest.mock('axios');
describe("users", () => {
  let response;
  beforeEach(() => {
    response = {
      data: [
        {
          id: 1,
          name: "Leanne Graham",
        },
        {
          id: 2,
          name: "Ervin Howell",
        },
        {
          id: 3,
          name: "Clementine Bauch",
        },
      ],
    };
  });

  test("fetching users", async () => {
    axios.get.mockReturnValue(response);
    render(<Users/>)
    const users = await screen.findAllByTestId('user-item');
    expect(users.length).toBe(3)
  });
});

I have no idea what to do (((


问:
Material UI components lose their styling after deployment, How to fix this?
I am using material UI drawer with styled-components. I have added some custom styling to navbar and drawer like changing background color of navbar and drawer etc. Everything works fine on localhost but when I deploy it anywhere like surge, vercel etc, somehow styling of these components gets removed. I have used several hosting services like firebase, surge, vercel and netlify. This issue persists no matter which hosting service I use. This is how my drawer looks like in localhost:

After deploying, this is how it looks like:

Here is my codesandbox: https://codesandbox.io/s/jolly-grass-l7v8mf?file=/demo.js

Here is deployment link: https://csb-l7v8mf-orpyzekrn-dev-sardarabdul.vercel.app/


问:
Android app does not support languages that are not in the android system for per-app languages
I have a problem, my application does not support languages that are not in the android system.
When I test the APK everything is fine, but after releasing to play store I have a problem.
I am trying to change languages programmatically.

 val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(languageCode) AppCompatDelegate.setApplicationLocales(appLocale)

I used the article https://developer.android.com/guide/topics/resources/app-languages

Edit

I resolved this problem added this:

```<code>android {
bundle {
    language {
        enableSplit = false
    }
}}
</code>```

Body:
I have a problem, my application does not support languages that are not in the android system.
When I test the APK everything is fine, but after releasing to play store I have a problem.
I am trying to change languages programmatically.

 val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(languageCode) AppCompatDelegate.setApplicationLocales(appLocale)

I used the article https://developer.android.com/guide/topics/resources/app-languages

Edit

I resolved this problem added this:

android {
bundle {
    language {
        enableSplit = false
    }
}}


问:
Bitbucket Pipelines export into variable using jq and xq causes error
When i running a pipeline in bitbucket  i want to export into variable using

```<code>export APEX_CLASSES=$(xq . < package/package.xml | jq '.Package.types | [.] | flatten | map(select(.name=="ApexClass")) | .[] | .members | [.] | flatten | map(select(. | index("*") | not)) | unique | join(",")' -r)
</code>```

but i got error in pipeline

```<code>parse error: Invalid numeric literal at line 1, column 5
</code>```

i tried to identify a error but i always get same error :(

When i add a escape \ before " i got this error

```<code>jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
.Package.types | [.] | flatten | map(select(.name==\"ApexClass\")) | .[] | .members | [.] | flatten | map(select(. | index(\"*\") | not)) | unique | join(\",\")
jq: 1 compile error
</code>```

This is package.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>AccountHelper</members>
        <members>BoatHelper</members>
        <members>CaseHelper</members>
        <name>ApexClass</name>
    </types>
    <version>57.0</version>
</Package>
</code>```

Body:
When i running a pipeline in bitbucket  i want to export into variable using

export APEX_CLASSES=$(xq . < package/package.xml | jq '.Package.types | [.] | flatten | map(select(.name=="ApexClass")) | .[] | .members | [.] | flatten | map(select(. | index("*") | not)) | unique | join(",")' -r)

but i got error in pipeline

parse error: Invalid numeric literal at line 1, column 5

i tried to identify a error but i always get same error :(

When i add a escape \ before " i got this error

jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
.Package.types | [.] | flatten | map(select(.name==\"ApexClass\")) | .[] | .members | [.] | flatten | map(select(. | index(\"*\") | not)) | unique | join(\",\")
jq: 1 compile error

This is package.xml

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>AccountHelper</members>
        <members>BoatHelper</members>
        <members>CaseHelper</members>
        <name>ApexClass</name>
    </types>
    <version>57.0</version>
</Package>


问:
API data to Bar graph in .Net MAUI
Am trying to create an app in .Net MAUI, i click a button, it fetches data from https://montemagno.com/monkeys.json and display a bar graph using LiveCharts. The bar graph must show the monkey name on x axis and monkey population on y axis. I am using the library of LiveChartsCore.SkiaSharpView. The graph is not being drawing because i have error with BarSeries. I tried to do the same code to display the data in a list and it is working fine. So the code is feching the data from the API. But not drawing the graph. Can you please help me.

I wonder if there is another way to draw a graph?

My Code-behind

```<code>private List<Monkey> monkeys;

    //The graph
    public ISeries[] Series { get; set; } =
    {
        new ColumnSeries<double>
        {
            Values = new ChartValues<double>(),
            Fill = new SolidColorPaint(SKColors.BlueViolet)
        }
    };
    public Axis[] XAxes { get; set; } =
    {
        new Axis
        {
            Name = "Monkey Names",
            Labels = new string[] { }
        }
    };
    public Axis[] YAxes { get; set; } =
    {
        new Axis
        {
            Name = "Monkeys Population",
            Labels = new string[] { }
        }
    };
    public MainPage()
    {
        BindingContext = this;
        InitializeComponent();
    }

    private async void FetchDataButton_Clicked(object sender, EventArgs e)
    {
        try
        {
            //Fetch data
            //var client = new HttpClient();
            //var stream = await client.GetStreamAsync("https://montemagno.com/monkeys.json");
            //var serializer = new DataContractJsonSerializer(typeof(List<Monkey>));
            //monkeys = serializer.ReadObject(stream) as List<Monkey>;

            var httpClient = new HttpClient();
            var url = "https://montemagno.com/monkeys.json";
            var response = await httpClient.GetAsync(url); //deserialize the JSON data into a List<Monkey> object
            monkeys = await response.Content.ReadFromJsonAsync<List<Monkey>>();

            var chartValues = new ChartValues<double>(); //is used to store the values of the chart, the population of the monkeys
            var labels = new string[monkeys.Count]; // string array that will store the X-axis of the chart. The size of the array is set to the number of monkeys in the list.

            //iterates through each monkey in the list of monkeys
            int i = 0;
            foreach (var monkey in monkeys)
            {
                chartValues.Add(monkey.Population);  //assigns the chartValues list to the Values property of the first series of the char
                labels[i] = monkey.Name; // assigns the labels array to the Labels property of the first X-axis of the chart.
                i++;
            }
            Series[0].Values = chartValues;
            XAxes[0].Labels = labels;
            PopulationChart.IsVisible = true;
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", "An error occured while fetching data", "OK");
        }

    }
    public class Monkey
    {
        public string Name { get; set; }
        public double Population { get; set; }
    }
}
</code>```

and the xaml file

```<code><ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <Button Grid.Row="0"
                x:Name="FetchDataButton"
                Text="Fetch Data"
                Clicked="FetchDataButton_Clicked"/>

            <lvc:CartesianChart Grid.Row="1"
                                x:Name="PopulationChart"
                                IsVisible="False"
                                Series="{Binding Series}"
                                YAxes="{Binding YAxes}"
                                XAxes="{Binding XAxes}">
            </lvc:CartesianChart>

        </Grid>
    </ContentPage.Content>

</code>```

Title: API data to Bar graph in .Net MAUI

Body:
Am trying to create an app in .Net MAUI, i click a button, it fetches data from https://montemagno.com/monkeys.json and display a bar graph using LiveCharts. The bar graph must show the monkey name on x axis and monkey population on y axis. I am using the library of LiveChartsCore.SkiaSharpView. The graph is not being drawing because i have error with BarSeries. I tried to do the same code to display the data in a list and it is working fine. So the code is feching the data from the API. But not drawing the graph. Can you please help me.

I wonder if there is another way to draw a graph?

My Code-behind

private List<Monkey> monkeys;

    //The graph
    public ISeries[] Series { get; set; } =
    {
        new ColumnSeries<double>
        {
            Values = new ChartValues<double>(),
            Fill = new SolidColorPaint(SKColors.BlueViolet)
        }
    };
    public Axis[] XAxes { get; set; } =
    {
        new Axis
        {
            Name = "Monkey Names",
            Labels = new string[] { }
        }
    };
    public Axis[] YAxes { get; set; } =
    {
        new Axis
        {
            Name = "Monkeys Population",
            Labels = new string[] { }
        }
    };
    public MainPage()
    {
        BindingContext = this;
        InitializeComponent();
    }

    private async void FetchDataButton_Clicked(object sender, EventArgs e)
    {
        try
        {
            //Fetch data
            //var client = new HttpClient();
            //var stream = await client.GetStreamAsync("https://montemagno.com/monkeys.json");
            //var serializer = new DataContractJsonSerializer(typeof(List<Monkey>));
            //monkeys = serializer.ReadObject(stream) as List<Monkey>;

            var httpClient = new HttpClient();
            var url = "https://montemagno.com/monkeys.json";
            var response = await httpClient.GetAsync(url); //deserialize the JSON data into a List<Monkey> object
            monkeys = await response.Content.ReadFromJsonAsync<List<Monkey>>();

            var chartValues = new ChartValues<double>(); //is used to store the values of the chart, the population of the monkeys
            var labels = new string[monkeys.Count]; // string array that will store the X-axis of the chart. The size of the array is set to the number of monkeys in the list.

            //iterates through each monkey in the list of monkeys
            int i = 0;
            foreach (var monkey in monkeys)
            {
                chartValues.Add(monkey.Population);  //assigns the chartValues list to the Values property of the first series of the char
                labels[i] = monkey.Name; // assigns the labels array to the Labels property of the first X-axis of the chart.
                i++;
            }
            Series[0].Values = chartValues;
            XAxes[0].Labels = labels;
            PopulationChart.IsVisible = true;
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", "An error occured while fetching data", "OK");
        }

    }
    public class Monkey
    {
        public string Name { get; set; }
        public double Population { get; set; }
    }
}

and the xaml file

<ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <Button Grid.Row="0"
                x:Name="FetchDataButton"
                Text="Fetch Data"
                Clicked="FetchDataButton_Clicked"/>

            <lvc:CartesianChart Grid.Row="1"
                                x:Name="PopulationChart"
                                IsVisible="False"
                                Series="{Binding Series}"
                                YAxes="{Binding YAxes}"
                                XAxes="{Binding XAxes}">
            </lvc:CartesianChart>

        </Grid>
    </ContentPage.Content>


问:
AppRunner build failure
Please help me with AWS App Runner. I tried various configuration options over a few days, but the build keeps failing :(

**
ERROR LOG**

```<code>01-12-2023 08:19:38 PM [AppRunner] Deployment with ID : 66482a95a0b640a48945c7d4b4714e91 failed.
01-12-2023 08:18:30 PM [AppRunner] Starting source code build.
01-12-2023 08:18:30 PM [AppRunner] Successfully Validate configuration file.
01-12-2023 08:18:29 PM [AppRunner] Successfully pulled source code.
01-12-2023 08:17:57 PM [AppRunner] Successfully created pipeline for automatic deployments.
01-12-2023 08:17:04 PM [AppRunner] Deployment Artifact :- Repo Type: Source; Repository: https://github.com/COMPANYNAME/BookingTool; Branch : UAT
01-12-2023 08:17:04 PM [AppRunner] Deployment with ID : 66482a95a0b640a48945c7d4b4714e91 started. Triggering event : SERVICE_CREATE
</code>```

GitHub repository path (Replaced my company name in the path)

```<code>https://github.com/COMPANYNAME/BookingTool/tree/UAT/BookingEngine/Src/Services/Master/Master.API
</code>```

AWS App Runner Values configured (I tried various commands for build and run)

CONNECT TO GITHUB

Repository: BookingTool Branch: UAT

RUNTIME: .NET 6

BUILD

```<code>dotnet publish -c Release -o out
</code>```
```<code>dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj  -c Release -o out
</code>```
```<code>dotnet publish BookingEngine/Src/Services/Master/Master.API.csproj  -c Release -o out
</code>```
```<code>dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj  -c Release
</code>```
```<code>dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj
</code>```

RUN

```<code>dotnet out/BookingEngine/Src/Services/Master/Master.API.dll
dotnet run
dotnet out
dotnet out/Master.API.dll
</code>```

PORT

```<code>8080
</code>```
```<code>9002
</code>```

Title: AppRunner build failure

Body:
Please help me with AWS App Runner. I tried various configuration options over a few days, but the build keeps failing :(

**
ERROR LOG**

01-12-2023 08:19:38 PM [AppRunner] Deployment with ID : 66482a95a0b640a48945c7d4b4714e91 failed.
01-12-2023 08:18:30 PM [AppRunner] Starting source code build.
01-12-2023 08:18:30 PM [AppRunner] Successfully Validate configuration file.
01-12-2023 08:18:29 PM [AppRunner] Successfully pulled source code.
01-12-2023 08:17:57 PM [AppRunner] Successfully created pipeline for automatic deployments.
01-12-2023 08:17:04 PM [AppRunner] Deployment Artifact :- Repo Type: Source; Repository: https://github.com/COMPANYNAME/BookingTool; Branch : UAT
01-12-2023 08:17:04 PM [AppRunner] Deployment with ID : 66482a95a0b640a48945c7d4b4714e91 started. Triggering event : SERVICE_CREATE

GitHub repository path (Replaced my company name in the path)

https://github.com/COMPANYNAME/BookingTool/tree/UAT/BookingEngine/Src/Services/Master/Master.API

AWS App Runner Values configured (I tried various commands for build and run)

CONNECT TO GITHUB

Repository: BookingTool Branch: UAT

RUNTIME: .NET 6

BUILD

dotnet publish -c Release -o out

dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj  -c Release -o out

dotnet publish BookingEngine/Src/Services/Master/Master.API.csproj  -c Release -o out

dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj  -c Release

dotnet publish /BookingEngine/Src/Services/Master/Master.API.csproj

RUN

dotnet out/BookingEngine/Src/Services/Master/Master.API.dll
dotnet run
dotnet out
dotnet out/Master.API.dll

PORT

8080

9002


问:
Performance impact of an ascending or a descending index during CUD in Mongo
In a mongo collection, createTime and lastUpdateTime are defined as timestamps and keeps increasing. User might query frequently about the latest updated value. Given the condition this collection might contain 100 millions of data, index shall be created.

Sample documents:
{ _id："1", a: "xx", b: "yy", createTime:ISODate("2022-05-16T06:07:47.280Z"), lastUpdateTime:ISODate("2022-05-16T06:07:47.280Z"), v: ["v1"] }
{ _id："2", a: "xx", b: "yy", createTime:ISODate("2022-05-16T06:07:47.280Z"), lastUpdateTime:ISODate("2022-05-17T07:07:47.280Z"), v: ["v1", "v2"] }

Typical query pattern: db["data"].find({a: "xx", "b": "yy", "createTime": { "$lte":ISODate("2022-05-16T06:07:47.280Z") }}）.sort({lastUpdateTime :-1}).limit(1)

There're two options about the index creation based on ESR rule.

CreateIndex({ a: 1, b: 1, lastUpdateTime :1,  createTime: 1})

CreateIndex({ a: 1, b: 1, lastUpdateTime :-1, createTime: 1}).

Both index can help this query. I don't assume there're obvious difference while I doubt there're different performance impact during insert/update/delete. Since timestamp is increasing by nature, I guess the "asc" index should be created. But not sure how to verify it.


问:
Click button in email to populate google sheet
I'm stuck I have done something similar before and it worked but this time round I keep getting a "Sorry, unable to open the file at present." error message.

I want to send an email to a number of participants and once they click on the button in the email my google sheet will update with a simple "Yes", my code is below for the sake completeness I have added everything apologies if it's all a bit much.

GAS code:

```<code>function sendChallengeEmail() {

  var url = 'https://script.google.com/macros/s/AKfycbzqVFeYC0O1PVHA051UxvrmdJgDJ9gyjhw5X7Lks6j5LGhmRpbCaRLVS38I--ySTLAS/exec'

  const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1NbDbt3IzcXBcZeIa2_XERql4AxnUOQyZDvNRTiaNVXg/edit?pli=1#gid=1386761827");
  const challenges = ss.getSheetByName("Challenges");
  const responses = ss.getSheetByName("Responses");

  var challengesLen = challenges.getLastRow();
  var challenge = '';
  var challengeCol;
  var date = Utilities.formatDate(new Date, "GMT", "dd/MM/yyyy").toString();

  for (var i = 1; i <= challengesLen; i++) {
    if (challenges.getRange(i,1).getValue() == date) {
      challenge = challenges.getRange(i,2).getValue();
    }
  }

  for (var j = 1; j <= responses.getLastColumn(); j++) {
    if (responses.getRange(1,j).getValue() == challenge) {
      challengeCol = j;
    }
  }

  var day = challenge.split(" ")[1];
  Logger.log(challenge);
  Logger.log(challengeCol);

  var data = responses.getRange(2,1,responses.getLastRow()-1,13).getValues();

  data.forEach(function(row, i) {
    var participant = row[1];
    var participantEmail = row[2]
    var emailSent = row[challengeCol - 2];

    Logger.log(row);
    Logger.log(emailSent);
    Logger.log(challengeCol-1);

    if (emailSent == '') {
      Logger.log(emailSent);
      var emailSentCol = challengeCol - 1;
      var workingRow = i + 2;

      var submit = url + "?submit=Yes" + "&challenge=" + challenge + "&r=" + workingRow + "&c=" + challengeCol;
      var templ = HtmlService.createTemplateFromFile('emailBody');
      templ.participant = participant;
      templ.day = day;
      templ.challenge = challenge;
      templ.submit = submit;

      var message = templ.evaluate().getContent();

      MailApp.sendEmail({
        to: participantEmail,
        subject: "test",
        htmlBody: message
      });

      var d = new Date();
      responses.getRange(workingRow, emailSentCol).setValue(d);
    };
  });
}

function doGet(e) {
  var answer = e.parameter.submit;
  var workingRow = e.parameter.r;
  var workingCol = e.parameter.c;

  responses.getRange(workingRow, workingCol).setValue(answer);

  var app = HtmlService.createHtmlOutput("Thank you!")

  return app

}
</code>```

HTML code:

<!DOCTYPE html>

    <base target="_top">

Hello <?= participant ?>

You are now on Day <?= day ?> of the challenge!

Today's challenge is:

    <?= challenge ?>

Don't forget to submit once you have completed your challenge!

     button id = "btn" onclick ="getElementById('btn').innerHTML='CONGRATULATIONS'" class="button">Challenge completed!

And finally how about sharing an image of your challenge :)

    <form>
      <label for = '"url " + <?= day ?>'>Enter image url here:
      <input type = "url <?= day ?>" class = textarea id = "url" name = "data[url <?= day ?>]">
      <button type = "submit" class="btn btn-primary btn-block">Submit</button>
    </form>

```

I am only logged into one google account I know this has been suggested in other posts.

Body:
I'm stuck I have done something similar before and it worked but this time round I keep getting a "Sorry, unable to open the file at present." error message.

I want to send an email to a number of participants and once they click on the button in the email my google sheet will update with a simple "Yes", my code is below for the sake completeness I have added everything apologies if it's all a bit much.

GAS code:

function sendChallengeEmail() {

  var url = 'https://script.google.com/macros/s/AKfycbzqVFeYC0O1PVHA051UxvrmdJgDJ9gyjhw5X7Lks6j5LGhmRpbCaRLVS38I--ySTLAS/exec'

  const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1NbDbt3IzcXBcZeIa2_XERql4AxnUOQyZDvNRTiaNVXg/edit?pli=1#gid=1386761827");
  const challenges = ss.getSheetByName("Challenges");
  const responses = ss.getSheetByName("Responses");

  var challengesLen = challenges.getLastRow();
  var challenge = '';
  var challengeCol;
  var date = Utilities.formatDate(new Date, "GMT", "dd/MM/yyyy").toString();

  for (var i = 1; i <= challengesLen; i++) {
    if (challenges.getRange(i,1).getValue() == date) {
      challenge = challenges.getRange(i,2).getValue();
    }
  }

  for (var j = 1; j <= responses.getLastColumn(); j++) {
    if (responses.getRange(1,j).getValue() == challenge) {
      challengeCol = j;
    }
  }

  var day = challenge.split(" ")[1];
  Logger.log(challenge);
  Logger.log(challengeCol);

  var data = responses.getRange(2,1,responses.getLastRow()-1,13).getValues();

  data.forEach(function(row, i) {
    var participant = row[1];
    var participantEmail = row[2]
    var emailSent = row[challengeCol - 2];

    Logger.log(row);
    Logger.log(emailSent);
    Logger.log(challengeCol-1);

    if (emailSent == '') {
      Logger.log(emailSent);
      var emailSentCol = challengeCol - 1;
      var workingRow = i + 2;

      var submit = url + "?submit=Yes" + "&challenge=" + challenge + "&r=" + workingRow + "&c=" + challengeCol;
      var templ = HtmlService.createTemplateFromFile('emailBody');
      templ.participant = participant;
      templ.day = day;
      templ.challenge = challenge;
      templ.submit = submit;

      var message = templ.evaluate().getContent();

      MailApp.sendEmail({
        to: participantEmail,
        subject: "test",
        htmlBody: message
      });

      var d = new Date();
      responses.getRange(workingRow, emailSentCol).setValue(d);
    };
  });
}

function doGet(e) {
  var answer = e.parameter.submit;
  var workingRow = e.parameter.r;
  var workingCol = e.parameter.c;

  responses.getRange(workingRow, workingCol).setValue(answer);

  var app = HtmlService.createHtmlOutput("Thank you!")

  return app

}

HTML code:

<!DOCTYPE html>

    <base target="_top">

Hello <?= participant ?>

You are now on Day <?= day ?> of the challenge!

Today's challenge is:

    <?= challenge ?>

Don't forget to submit once you have completed your challenge!

    <a href = <?= submit ?> button id = "btn" onclick ="getElementById('btn').innerHTML='CONGRATULATIONS'" class="button">Challenge completed!

And finally how about sharing an image of your challenge :)

    <form>
      <label for = '"url " + <?= day ?>'>Enter image url here:
      <input type = "url <?= day ?>" class = textarea id = "url" name = "data[url <?= day ?>]">
      <button type = "submit" class="btn btn-primary btn-block">Submit</button>
    </form>

I am only logged into one google account I know this has been suggested in other posts.


问:
Link to chat with message attached
I need to make html a tag with link to telegram chat, on click telegram suppose to open with prefilled message which will be defined in link.

Here is whatsapp implementation of what i wanna do:

```<code><a href="https://wa.me/<PHONE>?text=<TEXT>">Link</a>
</code>```

I tryed search google, but no luck.

Title: Link to chat with message attached

Body:
I need to make html a tag with link to telegram chat, on click telegram suppose to open with prefilled message which will be defined in link.

Here is whatsapp implementation of what i wanna do:

<a href="https://wa.me/<PHONE>?text=<TEXT>">Link

I tryed search google, but no luck.


问:
Pandas df.to_csv hangs, no error and not interruptable with ctrl + c
I have a dataframe which I would like to write to a csv file.

```<code>                        genus       species isolate strain               concatenated_annotation
AB269817.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
AJ867057.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867058.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867059.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867060.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
...                       ...           ...     ...    ...                                   ...
MG742125.1           Oscheius   myriophilus     nan    nan          Oscheius,myriophilus,nan,nan
MG865784.1  Parasitorhabditis        obtusa    O817    nan     Parasitorhabditis,obtusa,O817,nan
MW007714.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
MW007715.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
OK597215.1     Distolabrellus        veechi   HNK-2    nan       Distolabrellus,veechi,HNK-2,nan

[256 rows x 5 columns]
</code>```

I'm trying to write this to a csv file as follows  (note the commented line df.to_excel works):

```<code>with open("my_file.csv", "a") as f:
        df.to_csv(f, index=False)
        #df.to_excel(f, index=False)
</code>```

I did use the module hanging_threads to see where it is hanging as follows:

```<code>from hanging_threads import start_monitoring
start_monitoring(seconds_frozen=10, test_interval=100)
</code>```

I get following output and no errors from the script. I also can't interrupt the execution with ctrl +c:

```<code>---------Thread 139763701146048 "MainThread" hangs ---------
        File "/home/dslos/.virtualenvs/metabar/bin/metadb-annotate", line 33, in <module>
                sys.exit(load_entry_point('taxonomy', 'console_scripts', 'metadb-annotate')())
        File "/home/genomics/dslos/06_development/metabarcoding-pipelines/db_scripts/src/taxonomy/annotate.py", line 149, in main
                df.to_csv(f, index=False)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/generic.py", line 3551, in to_csv
                return DataFrameRenderer(formatter).to_csv(
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/format.py", line 1180, in to_csv
                csv_formatter.save()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 261, in save
                self._save()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 266, in _save
                self._save_body()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 304, in _save_body
                self._save_chunk(start_i, end_i)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 311, in _save_chunk
                res = df._mgr.to_native_types(**self._number_format)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/managers.py", line 473, in to_native_types
                return self.apply("to_native_types", **kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/managers.py", line 304, in apply
                applied = getattr(b, f)(**kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/blocks.py", line 634, in to_native_types
                result = to_native_types(self.values, na_rep=na_rep, quoting=quoting, **kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/blocks.py", line 2236, in to_native_types
                values[mask] = na_rep
</code>```

What could be the issue here?

I'm expecting it to write a csv file.

Body:
I have a dataframe which I would like to write to a csv file.

                        genus       species isolate strain               concatenated_annotation
AB269817.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
AJ867057.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867058.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867059.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
AJ867060.1        Pellioditis        marina     nan    nan            Pellioditis,marina,nan,nan
...                       ...           ...     ...    ...                                   ...
MG742125.1           Oscheius   myriophilus     nan    nan          Oscheius,myriophilus,nan,nan
MG865784.1  Parasitorhabditis        obtusa    O817    nan     Parasitorhabditis,obtusa,O817,nan
MW007714.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
MW007715.1    Teratorhabditis  synpapillata     nan    nan  Teratorhabditis,synpapillata,nan,nan
OK597215.1     Distolabrellus        veechi   HNK-2    nan       Distolabrellus,veechi,HNK-2,nan

[256 rows x 5 columns]

I'm trying to write this to a csv file as follows  (note the commented line df.to_excel works):

with open("my_file.csv", "a") as f:
        df.to_csv(f, index=False)
        #df.to_excel(f, index=False)

I did use the module hanging_threads to see where it is hanging as follows:

from hanging_threads import start_monitoring
start_monitoring(seconds_frozen=10, test_interval=100)

I get following output and no errors from the script. I also can't interrupt the execution with ctrl +c:

---------Thread 139763701146048 "MainThread" hangs ---------
        File "/home/dslos/.virtualenvs/metabar/bin/metadb-annotate", line 33, in <module>
                sys.exit(load_entry_point('taxonomy', 'console_scripts', 'metadb-annotate')())
        File "/home/genomics/dslos/06_development/metabarcoding-pipelines/db_scripts/src/taxonomy/annotate.py", line 149, in main
                df.to_csv(f, index=False)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/generic.py", line 3551, in to_csv
                return DataFrameRenderer(formatter).to_csv(
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/format.py", line 1180, in to_csv
                csv_formatter.save()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 261, in save
                self._save()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 266, in _save
                self._save_body()
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 304, in _save_body
                self._save_chunk(start_i, end_i)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/io/formats/csvs.py", line 311, in _save_chunk
                res = df._mgr.to_native_types(**self._number_format)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/managers.py", line 473, in to_native_types
                return self.apply("to_native_types", **kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/managers.py", line 304, in apply
                applied = getattr(b, f)(**kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/blocks.py", line 634, in to_native_types
                result = to_native_types(self.values, na_rep=na_rep, quoting=quoting, **kwargs)
        File "/home/dslos/.virtualenvs/metabar/lib/python3.10/site-packages/pandas/core/internals/blocks.py", line 2236, in to_native_types
                values[mask] = na_rep

What could be the issue here?

I'm expecting it to write a csv file.


问:
Generating text word by word for transformers
I’m currently using GPT-J for generating text as shown below. This works well but it takes up to 5 seconds to generate the 100 tokens.

Is it possible to do the generation word by word or sentence by sentence? Similar to what ChatGPT is doing (ChatGPT seems to produce the output word by word).

```<code>import transformers
from transformers import GPTJForCausalLM
config = transformers.GPTJConfig.from_pretrained("EleutherAI/gpt-j-6B")
tokenizer = transformers.AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B", pad_token='<|endoftext|>', eos_token='<|endoftext|>', truncation_side='left')
model = GPTJForCausalLM.from_pretrained(
            "EleutherAI/gpt-j-6B",
            revision="float16",
            torch_dtype=torch.float16,
            low_cpu_mem_usage=True,
            use_cache=True,
            gradient_checkpointing=True,
        )
model.to("cuda")
prompt = tokenizer("This is a test sentence, which should be completed", return_tensors='pt', truncation=True, max_length=2000)
prompt = {key: value.to("cuda") for key, value in prompt.items()}
out = model.generate(**prompt,
                     n=1,
                     min_length=16,
                     max_new_tokens=100,
                     do_sample=True,
                     top_k=15,
                     top_p=0.9,
                     batch_size=1,
                     temperature=1,
                     no_repeat_ngram_size=4,
                     clean_up_tokenization_spaces=True,
                     use_cache=True,
                     pad_token_id=tokenizer.eos_token_id,
                     )
 res = tokenizer.decode(out[0])
</code>```

Body:
I’m currently using GPT-J for generating text as shown below. This works well but it takes up to 5 seconds to generate the 100 tokens.

Is it possible to do the generation word by word or sentence by sentence? Similar to what ChatGPT is doing (ChatGPT seems to produce the output word by word).

import transformers
from transformers import GPTJForCausalLM
config = transformers.GPTJConfig.from_pretrained("EleutherAI/gpt-j-6B")
tokenizer = transformers.AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B", pad_token='<|endoftext|>', eos_token='<|endoftext|>', truncation_side='left')
model = GPTJForCausalLM.from_pretrained(
            "EleutherAI/gpt-j-6B",
            revision="float16",
            torch_dtype=torch.float16,
            low_cpu_mem_usage=True,
            use_cache=True,
            gradient_checkpointing=True,
        )
model.to("cuda")
prompt = tokenizer("This is a test sentence, which should be completed", return_tensors='pt', truncation=True, max_length=2000)
prompt = {key: value.to("cuda") for key, value in prompt.items()}
out = model.generate(**prompt,
                     n=1,
                     min_length=16,
                     max_new_tokens=100,
                     do_sample=True,
                     top_k=15,
                     top_p=0.9,
                     batch_size=1,
                     temperature=1,
                     no_repeat_ngram_size=4,
                     clean_up_tokenization_spaces=True,
                     use_cache=True,
                     pad_token_id=tokenizer.eos_token_id,
                     )
 res = tokenizer.decode(out[0])