问:
postgres server started to refuse connection
After ssh into the ubuntu 20.04 server running postgresql 14, the sudo -u Postgres sql Postgres command returns an error message:

```<code>psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
    Is the server running locally and accepting connections on that socket?
</code>```

Here is the pg_hba.conf:

```<code>local   all             all                                     trust #<<==changed from peer to trust. but error is the same
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256
#ssl
hostssl all             all             0.0.0.0/0               scram-sha-256 c>
</code>```

Here is the nodejs connection string:

```<code>const Sql = require("sequelize");  //sequelize 6.x
db = new Sql('mydb', 'postgres', `${process.env.DB_PASSWORD}`, {
        host: 'localhost',
        dialect: 'postgres',
        port:5432,
        //operatorsAliases: false
    } );
</code>```

The connection request initialized on the same server returns an error:

```<code>r]: connect ECONNREFUSED 127.0.0.1:5432
0|server  |     at Client._connectionCallback (/home/node-xyz/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:130:24)
0|server  |     at Client._handleErrorWhileConnecting (/home/node-xyz/node_modules/pg/lib/client.js:305:19)
0|server  |     at Client._handleErrorEvent (/home/node-xyz/node_modules/pg/lib/client.js:315:19)
0|server  |     at Connection.emit (node:events:513:28)
0|server  |     at Socket.reportStreamError (/home/node-xyz/node_modules/pg/lib/connection.js:52:12)
0|server  |     at Socket.emit (node:events:513:28)
0|server  |     at emitErrorNT (node:internal/streams/destroy:157:8)
0|server  |     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
0|server  |     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
0|server  |   parent: Error: connect ECONNREFUSED 127.0.0.1:5432
0|server  |       at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
0|server  |     errno: -111,
0|server  |     code: 'ECONNREFUSED',
0|server  |     syscall: 'connect',
0|server  |     address: '127.0.0.1',
0|server  |     port: 5432
0|server  |   },
0|server  |   original: Error: connect ECONNREFUSED 127.0.0.1:5432
</code>```

Body:
After ssh into the ubuntu 20.04 server running postgresql 14, the sudo -u Postgres sql Postgres command returns an error message:

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
    Is the server running locally and accepting connections on that socket?

Here is the pg_hba.conf:

local   all             all                                     trust #<<==changed from peer to trust. but error is the same
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256
#ssl
hostssl all             all             0.0.0.0/0               scram-sha-256 c>

Here is the nodejs connection string:

const Sql = require("sequelize");  //sequelize 6.x
db = new Sql('mydb', 'postgres', `${process.env.DB_PASSWORD}`, {
        host: 'localhost',
        dialect: 'postgres',
        port:5432,
        //operatorsAliases: false
    } );

The connection request initialized on the same server returns an error:

r]: connect ECONNREFUSED 127.0.0.1:5432
0|server  |     at Client._connectionCallback (/home/node-xyz/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:130:24)
0|server  |     at Client._handleErrorWhileConnecting (/home/node-xyz/node_modules/pg/lib/client.js:305:19)
0|server  |     at Client._handleErrorEvent (/home/node-xyz/node_modules/pg/lib/client.js:315:19)
0|server  |     at Connection.emit (node:events:513:28)
0|server  |     at Socket.reportStreamError (/home/node-xyz/node_modules/pg/lib/connection.js:52:12)
0|server  |     at Socket.emit (node:events:513:28)
0|server  |     at emitErrorNT (node:internal/streams/destroy:157:8)
0|server  |     at emitErrorCloseNT (node:internal/streams/destroy:122:3)
0|server  |     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
0|server  |   parent: Error: connect ECONNREFUSED 127.0.0.1:5432
0|server  |       at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
0|server  |     errno: -111,
0|server  |     code: 'ECONNREFUSED',
0|server  |     syscall: 'connect',
0|server  |     address: '127.0.0.1',
0|server  |     port: 5432
0|server  |   },
0|server  |   original: Error: connect ECONNREFUSED 127.0.0.1:5432


来源: stackexchange

问:
unicorn engine exception on mapped memory
I'm trying to emulate a MIPS 32 big-endian binary. Unfortunately, it throws an exception on the first instructions. I tried to start it from the second, and third instructions as well:

```<code>#!/bin/python3

from unicorn import *
from unicorn.mips_const import *

stack_size = 3 * 4096
load_address = 0x80023000
stack_base = load_address + 24*1024*1024 + 4096

def load_unicorn():
    mu = Uc(UC_ARCH_MIPS, UC_MODE_MIPS32 + UC_MODE_BIG_ENDIAN)
    er = open(r"blob", "rb")
    emulate_blob = er.read()
    mu.mem_map(load_address, 0x1000 + 24 * 1024 * 1024)
    mu.mem_map(stack_base, stack_size)
    mu.reg_write(UC_MIPS_REG_SP, stack_base + stack_size)

    mu.mem_write(load_address + 0xf00, emulate_blob)
    er.close()
    return mu

def decompress(mu):
    decompress_start = 0x800246AC
    decompress_end = 0x80024730

    buffer_address = 0x20000000
    buffer_size = 20 * 1024 * 1024 * 4 #0x2000000

    mu.mem_map(buffer_address, buffer_size)

    dest_buffer_address = buffer_address

    mu.reg_write(UC_MIPS_REG_A0, 0x8002917c)
    mu.reg_write(UC_MIPS_REG_A1, 0xD4AAEBC)
    mu.reg_write(UC_MIPS_REG_A2, dest_buffer_address)
    mu.reg_write(UC_MIPS_REG_A3, buffer_size)
    #mu.reg_write(UC_MIPS_REG_PC, decompress_start)

    mu.mem_write(stack_base, b"\x00" * stack_size)
    try:
        mu.emu_start(decompress_start, decompress_end)
    except Exception as e:
        print(e)
        print("IP: 0x{:x}".format(mu.reg_read(UC_MIPS_REG_PC)))

    total_size = mu.reg_read(UC_MIPS_REG_S5)
    decompressed_data = mu.mem_read(dest_buffer_address, total_size)
    return decompressed_data

memory_unit = load_unicorn()
data = decompress(memory_unit)
</code>```

When I read the memory at decompress_start (print(mu.mem_read(decompress_start,1024))), I get the following:
bytearray(b'\'\xbd\x00(\'\xbd\xff\xb8\x8f\xa3...
which corresponds correctly to the instructions in this code (\x27\xbd\xff\xb8 is addiu sp, sp, -0x48)

What could be wrong here? thanks!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to emulate a MIPS 32 big-endian binary. Unfortunately, it throws an exception on the first instructions. I tried to start it from the second, and third instructions as well:

#!/bin/python3

from unicorn import *
from unicorn.mips_const import *

stack_size = 3 * 4096
load_address = 0x80023000
stack_base = load_address + 24*1024*1024 + 4096

def load_unicorn():
    mu = Uc(UC_ARCH_MIPS, UC_MODE_MIPS32 + UC_MODE_BIG_ENDIAN)
    er = open(r"blob", "rb")
    emulate_blob = er.read()
    mu.mem_map(load_address, 0x1000 + 24 * 1024 * 1024)
    mu.mem_map(stack_base, stack_size)
    mu.reg_write(UC_MIPS_REG_SP, stack_base + stack_size)

    mu.mem_write(load_address + 0xf00, emulate_blob)
    er.close()
    return mu

def decompress(mu):
    decompress_start = 0x800246AC
    decompress_end = 0x80024730

    buffer_address = 0x20000000
    buffer_size = 20 * 1024 * 1024 * 4 #0x2000000

    mu.mem_map(buffer_address, buffer_size)

    dest_buffer_address = buffer_address

    mu.reg_write(UC_MIPS_REG_A0, 0x8002917c)
    mu.reg_write(UC_MIPS_REG_A1, 0xD4AAEBC)
    mu.reg_write(UC_MIPS_REG_A2, dest_buffer_address)
    mu.reg_write(UC_MIPS_REG_A3, buffer_size)
    #mu.reg_write(UC_MIPS_REG_PC, decompress_start)

    mu.mem_write(stack_base, b"\x00" * stack_size)
    try:
        mu.emu_start(decompress_start, decompress_end)
    except Exception as e:
        print(e)
        print("IP: 0x{:x}".format(mu.reg_read(UC_MIPS_REG_PC)))

    total_size = mu.reg_read(UC_MIPS_REG_S5)
    decompressed_data = mu.mem_read(dest_buffer_address, total_size)
    return decompressed_data

memory_unit = load_unicorn()
data = decompress(memory_unit)

When I read the memory at decompress_start (print(mu.mem_read(decompress_start,1024))), I get the following:
bytearray(b'\'\xbd\x00(\'\xbd\xff\xb8\x8f\xa3...
which corresponds correctly to the instructions in this code (\x27\xbd\xff\xb8 is addiu sp, sp, -0x48)

What could be wrong here? thanks!


问:
confluent_kafka python consumer.poll() function exits the entire code
I am referring to this tutorial for kafka which I have changed the video frames to image inputs. In my case, consumer.poll() does not return anything and breaks out of the code. In the docker terminal displays this:

```<code>kafka1    | [2023-01-10 07:21:30,719] INFO [GroupCoordinator 1]: Dynamic member with unknown member id joins group kafka-cam in Empty state. Created a new member id rdkafka-f0ea3fd0-2eef-494d-bbe5-1acd9db067c4 and request the member to rejoin with this id. (kafka.coordinator.group.GroupCoordinator)
kafka1    | [2023-01-10 07:21:30,721] INFO [GroupCoordinator 1]: Preparing to rebalance group kafka-cam in state PreparingRebalance with old generation 0 (__consumer_offsets-24) (reason: Adding new member rdkafka-f0ea3fd0-2eef-494d-bbe5-1acd9db067c4 with group instance id None; client reason: not provided) (kafka.coordinator.group.GroupCoordinator)
kafka1    | [2023-01-10 07:21:33,722] INFO [GroupCoordinator 1]: Stabilized group kafka-cam generation 1 (__consumer_offsets-24) with 1 members (kafka.coordinator.group.GroupCoordinator)(kafka.coordinator.group.GroupCoordinator)
</code>```

But it does not actually run the code below:

```<code>while True:
     print("entered")
     msg = consumer.poll(100)
     print(msg)
     if msg == None:
         continue
</code>```

as consumer.poll exits the entire code as a whole and does not run anything after that.

According to the printing statements I have added for testing purposes, msg should either return None or the value of whatever the consumer polls. However, it breaks out of the code.

```<code>python consumer.py
Creating consumer thread...
Starting the consumer thread...
entered
</code>```

As shown above, it prints entered but does not run the print(msg) after calling poll.

The poll function should only return None or msg, otherwise throw an exception. It should not break out of the code. Anyone experiencing this issue? I might be doing something wrong as this is the first time I am using kafka.

My Producer file:

```<code>from producer_config import config as producer_config
from confluent_kafka import Producer
import os
import concurrent.futures
import cv2
from utils import *
from glob import glob

class ProducerThread:
    def __init__(self, config):
        self.producer = Producer(config)

    def publishImage(self, img_path):
        img = cv2.imread(img_path)
        print(img.shape)
        img_name = os.path.basename(img_path).split(".")[0]
        img_bytes = serializeImg(img)
        self.producer.produce(
            topic = "multi-cam-stream",
            value = img_bytes,
            on_delivery = delivery_report,
            timestamp = 0,
            headers = {
                "img_name": str.encode(img_name)
            }
        )
        self.producer.poll(0.5)
        return

    def start(self, img_paths):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            executor.map(self.publishImage, img_paths)

        self.producer.flush() # push all the remaining msgs in the queue
        print("Finished")

if __name__ == "__main__":
    img_dir = "imgs/"
    img_paths = glob(img_dir + "*.JPG")
    producer_thread = ProducerThread(producer_config)
    producer_thread.start(img_paths)
</code>```

Producer Config:

```<code>config = {
    'bootstrap.servers': '127.0.0.1:9092',
    'group.id': 'kafka-cam',
    'enable.auto.commit': False,
    'default.topic.config': {'auto.offset.reset': 'earliest'},
}
</code>```

My Consumer file:

```<code>import threading
from confluent_kafka import Consumer, KafkaError, KafkaException
from consumer_config import config as consumer_config
from utils import *
from pymongo import MongoClient
from dotenv import load_dotenv

import os
import base64
import requests
import json

class ConsumerThread:
    def __init__(self, config, topic, batch_size, model_api, db):
        self.config = config
        self.topic = topic
        self.batch_size = batch_size
        self.model_api = model_api
        self.db = db

    def read_data(self):
        consumer = Consumer(self.config)
        consumer.subscribe(self.topic)
        self.run(consumer,0)

    def run(self, consumer, msg_count):
        try:
            coll = db.outputs
            imgs = []
            # msg = consumer.poll(2)
            # print(msg)
            while True:
                print("entered")
                msg = consumer.poll(timeout=3)
                # why did it skip after poll?
                print(msg)
                if msg == None:
                    print("msg is empty")
                    continue
                elif msg.error() is not None:
                    raise KafkaException(msg.error())
                elif msg.error() == None:
                    # msg.value() returns bytes
                    img_bytes = msg.value()
                    # img_bytes = base64.b64decode(img_bytes)
                    imgs.append(img_bytes)
                    print(len(imgs))

                    msg_count += 1
                    if msg_count % self.batch_size == 0:
                        print(len(imgs))
                        files = {
                            f"{_id}": img
                            for _id, img in enumerate(imgs)
                        }
                        # feed it to the model api
                        response = requests.post(MODEL_API, files=files)
                        results = json.loads(response.content)
                        for _id in files:
                            img_str = base64.b64encode(files[_id])
                            img = {
                                "image": img_str,
                                "result": results[int(_id)]
                                }
                            coll.insert_one(img)

                        consumer.commit(asynchronous=False)
                        # msg_count = 0
                    elif msg.error().code() == KafkaError._PARTITION_EOF:
                        print('End of partition reached {0}/{1}'
                            .format(msg.topic(), msg.partition()))
                    else:
                        print('Error occured: {0}'.format(msg.error().str()))
                print(msg_count)

        except KeyboardInterrupt:
            print("Detected Keyboard Interrupt. Quitting...")
            pass

        finally:
            print("closing")
            consumer.close()

    def start(self, numThreads):
        for _ in range(numThreads):
            t = threading.Thread(target=self.read_data)
            t.daemon = True
            t.start()

if __name__ == "__main__":
    load_dotenv()
    topic = ["multi-cam-stream"]
    MODEL_API = os.environ["MODEL_API"]
    MONGODB_URI = os.environ["MONGODB_URI"]
    client = MongoClient(MONGODB_URI)
    db = client.smart_agriculture

    print("Creating consumer thread...")
    consumer_thread = ConsumerThread(consumer_config, topic, 4, MODEL_API, db)
    print("Starting the consumer thread...")
    consumer_thread.start(1)
</code>```

Consumer Config:

```<code>config = {
    'bootstrap.servers': '127.0.0.1:9092',
    'group.id': 'kafka-cam',
    'enable.auto.commit': False,
    'default.topic.config': {'auto.offset.reset': 'earliest'},
    'max.poll.interval.ms': 20000,
    'session.timeout.ms': 10000,
    'fetch.message.max.bytes': 10000000,
    'max.partition.fetch.bytes': 1000000
}
</code>```

Utils.py:

```<code>import logging
import cv2
import json

logging.basicConfig(level=logging.INFO, format='%(name)s - %(levelname)s - %(message)s')

def delivery_report(err, msg):
    if err:
        logging.error("Failed to deliver message: {0}: {1}"
            .format(msg.value(), err.str()))
    else:
        logging.info(f"msg produced. \n"
                    f"Topic: {msg.topic()} \n" +
                    f"Partition: {msg.partition()} \n" +
                    f"Offset: {msg.offset()} \n" +
                    f"Timestamp: {msg.timestamp()} \n")

def serializeImg(img):
    _, img_buffer_arr = cv2.imencode(".jpg", img)
    img_bytes = img_buffer_arr.tobytes()
    return img_bytes

def jsonify(img):
    return json.dumps(img)
</code>```

Body:
I am referring to this tutorial for kafka which I have changed the video frames to image inputs. In my case, consumer.poll() does not return anything and breaks out of the code. In the docker terminal displays this:

kafka1    | [2023-01-10 07:21:30,719] INFO [GroupCoordinator 1]: Dynamic member with unknown member id joins group kafka-cam in Empty state. Created a new member id rdkafka-f0ea3fd0-2eef-494d-bbe5-1acd9db067c4 and request the member to rejoin with this id. (kafka.coordinator.group.GroupCoordinator)
kafka1    | [2023-01-10 07:21:30,721] INFO [GroupCoordinator 1]: Preparing to rebalance group kafka-cam in state PreparingRebalance with old generation 0 (__consumer_offsets-24) (reason: Adding new member rdkafka-f0ea3fd0-2eef-494d-bbe5-1acd9db067c4 with group instance id None; client reason: not provided) (kafka.coordinator.group.GroupCoordinator)
kafka1    | [2023-01-10 07:21:33,722] INFO [GroupCoordinator 1]: Stabilized group kafka-cam generation 1 (__consumer_offsets-24) with 1 members (kafka.coordinator.group.GroupCoordinator)(kafka.coordinator.group.GroupCoordinator)

But it does not actually run the code below:

while True:
     print("entered")
     msg = consumer.poll(100)
     print(msg)
     if msg == None:
         continue

as consumer.poll exits the entire code as a whole and does not run anything after that.

According to the printing statements I have added for testing purposes, msg should either return None or the value of whatever the consumer polls. However, it breaks out of the code.

python consumer.py
Creating consumer thread...
Starting the consumer thread...
entered

As shown above, it prints entered but does not run the print(msg) after calling poll.

The poll function should only return None or msg, otherwise throw an exception. It should not break out of the code. Anyone experiencing this issue? I might be doing something wrong as this is the first time I am using kafka.

My Producer file:

from producer_config import config as producer_config
from confluent_kafka import Producer
import os
import concurrent.futures
import cv2
from utils import *
from glob import glob

class ProducerThread:
    def __init__(self, config):
        self.producer = Producer(config)

    def publishImage(self, img_path):
        img = cv2.imread(img_path)
        print(img.shape)
        img_name = os.path.basename(img_path).split(".")[0]
        img_bytes = serializeImg(img)
        self.producer.produce(
            topic = "multi-cam-stream",
            value = img_bytes,
            on_delivery = delivery_report,
            timestamp = 0,
            headers = {
                "img_name": str.encode(img_name)
            }
        )
        self.producer.poll(0.5)
        return

    def start(self, img_paths):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            executor.map(self.publishImage, img_paths)

        self.producer.flush() # push all the remaining msgs in the queue
        print("Finished")

if __name__ == "__main__":
    img_dir = "imgs/"
    img_paths = glob(img_dir + "*.JPG")
    producer_thread = ProducerThread(producer_config)
    producer_thread.start(img_paths)

Producer Config:

config = {
    'bootstrap.servers': '127.0.0.1:9092',
    'group.id': 'kafka-cam',
    'enable.auto.commit': False,
    'default.topic.config': {'auto.offset.reset': 'earliest'},
}

My Consumer file:

import threading
from confluent_kafka import Consumer, KafkaError, KafkaException
from consumer_config import config as consumer_config
from utils import *
from pymongo import MongoClient
from dotenv import load_dotenv

import os
import base64
import requests
import json

class ConsumerThread:
    def __init__(self, config, topic, batch_size, model_api, db):
        self.config = config
        self.topic = topic
        self.batch_size = batch_size
        self.model_api = model_api
        self.db = db

    def read_data(self):
        consumer = Consumer(self.config)
        consumer.subscribe(self.topic)
        self.run(consumer,0)

    def run(self, consumer, msg_count):
        try:
            coll = db.outputs
            imgs = []
            # msg = consumer.poll(2)
            # print(msg)
            while True:
                print("entered")
                msg = consumer.poll(timeout=3)
                # why did it skip after poll?
                print(msg)
                if msg == None:
                    print("msg is empty")
                    continue
                elif msg.error() is not None:
                    raise KafkaException(msg.error())
                elif msg.error() == None:
                    # msg.value() returns bytes
                    img_bytes = msg.value()
                    # img_bytes = base64.b64decode(img_bytes)
                    imgs.append(img_bytes)
                    print(len(imgs))

                    msg_count += 1
                    if msg_count % self.batch_size == 0:
                        print(len(imgs))
                        files = {
                            f"{_id}": img
                            for _id, img in enumerate(imgs)
                        }
                        # feed it to the model api
                        response = requests.post(MODEL_API, files=files)
                        results = json.loads(response.content)
                        for _id in files:
                            img_str = base64.b64encode(files[_id])
                            img = {
                                "image": img_str,
                                "result": results[int(_id)]
                                }
                            coll.insert_one(img)

                        consumer.commit(asynchronous=False)
                        # msg_count = 0
                    elif msg.error().code() == KafkaError._PARTITION_EOF:
                        print('End of partition reached {0}/{1}'
                            .format(msg.topic(), msg.partition()))
                    else:
                        print('Error occured: {0}'.format(msg.error().str()))
                print(msg_count)

        except KeyboardInterrupt:
            print("Detected Keyboard Interrupt. Quitting...")
            pass

        finally:
            print("closing")
            consumer.close()

    def start(self, numThreads):
        for _ in range(numThreads):
            t = threading.Thread(target=self.read_data)
            t.daemon = True
            t.start()

if __name__ == "__main__":
    load_dotenv()
    topic = ["multi-cam-stream"]
    MODEL_API = os.environ["MODEL_API"]
    MONGODB_URI = os.environ["MONGODB_URI"]
    client = MongoClient(MONGODB_URI)
    db = client.smart_agriculture

    print("Creating consumer thread...")
    consumer_thread = ConsumerThread(consumer_config, topic, 4, MODEL_API, db)
    print("Starting the consumer thread...")
    consumer_thread.start(1)

Consumer Config:

config = {
    'bootstrap.servers': '127.0.0.1:9092',
    'group.id': 'kafka-cam',
    'enable.auto.commit': False,
    'default.topic.config': {'auto.offset.reset': 'earliest'},
    'max.poll.interval.ms': 20000,
    'session.timeout.ms': 10000,
    'fetch.message.max.bytes': 10000000,
    'max.partition.fetch.bytes': 1000000
}

Utils.py:

import logging
import cv2
import json

logging.basicConfig(level=logging.INFO, format='%(name)s - %(levelname)s - %(message)s')

def delivery_report(err, msg):
    if err:
        logging.error("Failed to deliver message: {0}: {1}"
            .format(msg.value(), err.str()))
    else:
        logging.info(f"msg produced. \n"
                    f"Topic: {msg.topic()} \n" +
                    f"Partition: {msg.partition()} \n" +
                    f"Offset: {msg.offset()} \n" +
                    f"Timestamp: {msg.timestamp()} \n")

def serializeImg(img):
    _, img_buffer_arr = cv2.imencode(".jpg", img)
    img_bytes = img_buffer_arr.tobytes()
    return img_bytes

def jsonify(img):
    return json.dumps(img)


问:
Go Gota: Getting "wrong dimensions" error while running "mutate" to create a new col
I have a dataframe df that has two columns, i.e. A and B. I am trying to create a new column and adding it to the df like below:

```<code>logFunc := func(s series.Series) series.Series {
    floats := s.Float()
    outCol := []float64 {}
    for _, f := range floats {
        outCol = append(outCol, math.Ceil(1 - math.Log(f)))
    }
    return series.Floats(outCol)
}

newCol := df.Select("B").rapply(logFunc)

newDF := df.mutate(Series.New(newCol, series.Float, "C")
fmt.Println(newDF)
</code>```

But I am getting the below error:

```<code>DataFrame error: mutate: wrong dimensions
</code>```

Any help in this regard will be wonderful. Thanks

When I checked through the code of Gota and found this:

```<code>func (df DataFrame) Mutate(s series.Series) DataFrame {
        ...

    if s.Len() != df.nrows {
        return DataFrame{Err: fmt.Errorf("mutate: wrong dimensions")}
    }
</code>```

This means that if the length of the series and nrows of df doesn't match, it throws this error. But the way I am building this, they should match. Not sure how this can be solved.

I am expecting the newDF to have the new column alongside others.

Edit:

I figured out the issue here. The output of logFunc is not series but a dataframe. Now the question is how can we get the series out of the dataframe.

Body:
I have a dataframe df that has two columns, i.e. A and B. I am trying to create a new column and adding it to the df like below:

logFunc := func(s series.Series) series.Series {
    floats := s.Float()
    outCol := []float64 {}
    for _, f := range floats {
        outCol = append(outCol, math.Ceil(1 - math.Log(f)))
    }
    return series.Floats(outCol)
}

newCol := df.Select("B").rapply(logFunc)

newDF := df.mutate(Series.New(newCol, series.Float, "C")
fmt.Println(newDF)

But I am getting the below error:

DataFrame error: mutate: wrong dimensions

Any help in this regard will be wonderful. Thanks

When I checked through the code of Gota and found this:

func (df DataFrame) Mutate(s series.Series) DataFrame {
        ...

    if s.Len() != df.nrows {
        return DataFrame{Err: fmt.Errorf("mutate: wrong dimensions")}
    }

This means that if the length of the series and nrows of df doesn't match, it throws this error. But the way I am building this, they should match. Not sure how this can be solved.

I am expecting the newDF to have the new column alongside others.

Edit:

I figured out the issue here. The output of logFunc is not series but a dataframe. Now the question is how can we get the series out of the dataframe.


问:
How can I find the GCP Sku Description for an specific sku
As I am using this api :

https://cloud.google.com/billing/docs/reference/rest/v1/services.skus/list?apix_params=%7B%22parent%22%3A%22services%2F6F81-5844-456A%22%7D

In this api, all the GCP sku's are listed and it is more than 20k lines, So I am finding it difficult to Find the specific sku description as it is required for my work.

This api code return all the sku's list, but I want to search for an specific sku and get that sku's description.

For example : c2d-highmem-2

code :

```<code>with build("cloudbilling", "v1", credentials=credentials) as service:
    service_name = "services/" + service_id
    if page_token:
        request = service.services().skus().list(parent=service_name,
                                                 pageToken=page_token).execute()
    else:
        request = service.services().skus().list(parent=service_name).execute()
return request
</code>```

Body:
As I am using this api :

https://cloud.google.com/billing/docs/reference/rest/v1/services.skus/list?apix_params=%7B%22parent%22%3A%22services%2F6F81-5844-456A%22%7D

In this api, all the GCP sku's are listed and it is more than 20k lines, So I am finding it difficult to Find the specific sku description as it is required for my work.

This api code return all the sku's list, but I want to search for an specific sku and get that sku's description.

For example : c2d-highmem-2

code :

with build("cloudbilling", "v1", credentials=credentials) as service:
    service_name = "services/" + service_id
    if page_token:
        request = service.services().skus().list(parent=service_name,
                                                 pageToken=page_token).execute()
    else:
        request = service.services().skus().list(parent=service_name).execute()
return request


问:
Makefile:19: *** missing separator. Stop
I'm trying to compile multiple files in the same time but I don't know why the client command doesn't compile, but when I run it separately in the terminal it works at it should be.</p>
```<code>CC = gcc

UTILS = utils/*.c
ENTRY = main.c
TARGET = bin/main.exe

CLIENT_ENTRY = server/client.c
CLIENT_TARGET = bin/client.exe

SERVER_ENTRY = server/server.c
SERVER_TARGET = bin/server.exe

terminal:
    $(CC) $(UTILS) $(ENTRY) -o $(TARGET) -lreadline

client:
    $(CC) $(CLIENT_ENTRY) -o $(CLIENT_TARGET)

all: terminal client
</code>```

Body:
I'm trying to compile multiple files in the same time but I don't know why the client command doesn't compile, but when I run it separately in the terminal it works at it should be.

CC = gcc

UTILS = utils/*.c
ENTRY = main.c
TARGET = bin/main.exe

CLIENT_ENTRY = server/client.c
CLIENT_TARGET = bin/client.exe

SERVER_ENTRY = server/server.c
SERVER_TARGET = bin/server.exe

terminal:
    $(CC) $(UTILS) $(ENTRY) -o $(TARGET) -lreadline

client:
    $(CC) $(CLIENT_ENTRY) -o $(CLIENT_TARGET)

all: terminal client


问:
How to visualize large input logs (3GB: JSON / SSL logs)
I am looking for best methods to visualize data in charts or graphs using a large SSL request log file as input.  I am able to parse the data into JSON if this makes it easier, however any suggestions on alternatives to parse SSL into json is very much appreciated as well.

I have attempted using

SSL logs > JSON > prometheus > Grafana

SSL logs > filebeat > logstash > elasticsearch > kibana

Are there any other alternatives to these?

Thank you,


问:
Docker content is not rendered in the browser
I am using Ubuntu 22.04.1.

Recently I’ve had the problem that Docker containers that were already working can still be started as usual, but the browser shows a white background.

Only the icon in the browser tab is displayed.

This applies to the following addresses:

https://localhost
http://localhost
http://127.0.0.1
https://127.0.0.1
http://127.0.1.1
https://127.0.1.1
```

What can I do?

Body:
I am using Ubuntu 22.04.1.

Recently I’ve had the problem that Docker containers that were already working can still be started as usual, but the browser shows a white background.

Only the icon in the browser tab is displayed.

This applies to the following addresses:

https://localhost
http://localhost
http://127.0.0.1
https://127.0.0.1
http://127.0.1.1
https://127.0.1.1

What can I do?


问:
How to resolve the issue > Cannot read properties of undefined (reading 'native') with log4js implementation in cypress?

JSON data in json file:

{
"appenders": {
"out": {"type": "console", "layout": { "type": "coloured" } },
"app": {"type": "dateFile",
"filename": "cypress-logs/logger/info.log",
"maxLogSize": 10485760,
"layout":
{"type":"pattern", "pattern":"[%d{dd-MM-yyyy hh:mm:ss}] [%p] - %m"}
}
},
"categories": {
"default": { "appenders": ["out", "app"], "level": "info" }
}
}

.js file code:

```<code>"use strict";

function log4js_logger() {
    var log4js = require("log4js");  //importing log4js
    log4js.configure("cypress/fixtures/log4js.json");  //loading the json data here
    var logs = log4js.getLogger();
    //logs.info("Logger has implemented !!")
    return logs;
}

module.exports = {log4js_logger}
</code>```

js file where I'm using this logger.info:
---------------------------------------------

```<code>"use strict";
var logGenerator = require("../generic_utils/logger")
var logger = logGenerator.log4js_logger()

-----some js functions ---------------------------
-----using logger.info() within those functions---
</code>```

Error when running cypress test:

An uncaught error was detected outside of a test:
TypeError: The following error originated from your test code, not from Cypress.

Cannot read properties of undefined (reading 'native')

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
at ./node_modules/streamroller/node_modules/fs-extra/lib/fs/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:49841:24)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at ./node_modules/streamroller/node_modules/fs-extra/lib/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:49861:3)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at Object.eval (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48187:12)
at ./node_modules/streamroller/lib/RollingFileWriteStream.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48525:30)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at ./node_modules/streamroller/lib/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48694:27)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at Object.eval (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:44945:17)

Observation:

when I'm running js file with node command where log4js code is present, It is working fine but giving above error when running the cypress test

Body:
JSON data in json file:

{
"appenders": {
"out": {"type": "console", "layout": { "type": "coloured" } },
"app": {"type": "dateFile",
"filename": "cypress-logs/logger/info.log",
"maxLogSize": 10485760,
"layout":
{"type":"pattern", "pattern":"[%d{dd-MM-yyyy hh:mm:ss}] [%p] - %m"}
}
},
"categories": {
"default": { "appenders": ["out", "app"], "level": "info" }
}
}

.js file code:

"use strict";

function log4js_logger() {
    var log4js = require("log4js");  //importing log4js
    log4js.configure("cypress/fixtures/log4js.json");  //loading the json data here
    var logs = log4js.getLogger();
    //logs.info("Logger has implemented !!")
    return logs;
}

module.exports = {log4js_logger}

js file where I'm using this logger.info:
---------------------------------------------

"use strict";
var logGenerator = require("../generic_utils/logger")
var logger = logGenerator.log4js_logger()

-----some js functions ---------------------------
-----using logger.info() within those functions---

Error when running cypress test:

An uncaught error was detected outside of a test:
TypeError: The following error originated from your test code, not from Cypress.

Cannot read properties of undefined (reading 'native')

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
at ./node_modules/streamroller/node_modules/fs-extra/lib/fs/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:49841:24)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at ./node_modules/streamroller/node_modules/fs-extra/lib/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:49861:3)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at Object.eval (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48187:12)
at ./node_modules/streamroller/lib/RollingFileWriteStream.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48525:30)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at ./node_modules/streamroller/lib/index.js (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:48694:27)
at webpack_require (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:20:30)
at Object.eval (https://mcmp-cd2-int-testfra-apiauto.multicloud-ibm.com/__cypress/tests?p=cypress\e2e\common_inventory\aws\awsInventoryResourceDetails_cy.js:44945:17)

Observation:

when I'm running js file with node command where log4js code is present, It is working fine but giving above error when running the cypress test


问:
Get a column from a table using alaise with where condition
```<code>select column name
from MTL_SYSTEM_ITEMS_INTERFACE
where column name = 'divergence'(select divergence  as <h1>divergence</h1> from MTL_SYSTEM_ITEMS_INTERFACE)
</code>```

I need a column from a table using where condition that column name will show in alaise name

Body:
select column name
from MTL_SYSTEM_ITEMS_INTERFACE
where column name = 'divergence'(select divergence  as
divergence
 from MTL_SYSTEM_ITEMS_INTERFACE)

I need a column from a table using where condition that column name will show in alaise name


问:
assert_frame_equal is returning an error even though both the dataframes are identical in terms of data, column datatypes
I have 2 dataframes (DF1 and DF2), one created from sqllite select query (DF1) and another one from directly from the csv (DF2). The data in the sqllite table is inserted from the same csv that is used while reading it directly.

Some of the column names dtype were different so I changed the dtypes of the columns in DF2 as well.

e.g. task6_my['year'] = task6_my['year'].astype('int64') since dtype of engines column in the sqllite table is int whereas it was float64. This way I have done it for all the columns whereever there was a mismatch.(I am checking it through task6_sql.dtypes, task6_my.dtypes and it tells me which columns have a different dtypes.)

Once I pass the DF1, DF2 in assert_frame_equal it throws an exception:

AssertionError: DataFrame.iloc[:, 5] (column name="engines") are different

DataFrame.iloc[:, 5] (column name="engines") values are different (100.0 %)
[index]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
[left]:  [1, 2, 2, 2, 1, 4, 1, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2]
[right]: [1, 2, 2, 2, 1, 4, 1, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2]

In the engines column of both the DFs, indexes, column_names and even the values are identical. I have even tried setting check_dtype = False, check_names = False along with atol = 0.001 or rtol=1e-5. But none seems to be working.


问:
TestingLibraryElementError: Unable to find an element with the text:
I'm working on a React nx project and one of my test case failed giving the following error.

App › should have a greeting as the title

```<code>TestingLibraryElementError: Unable to find an element with the text: /Welcome shell/gi. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
</code>```

this is my test case

app.spec.tsx

```<code>it('should have a greeting as the title', () => {

    const { getByText } = render(

      <Provider store={store}>

      <BrowserRouter>

        <App />

      </BrowserRouter>

      </Provider>

    );

    expect(getByText(/Welcome shell/gi)).toBeTruthy();

  });
</code>```

what's the error in getByText? Can someone help me?

Body:
I'm working on a React nx project and one of my test case failed giving the following error.

App › should have a greeting as the title

TestingLibraryElementError: Unable to find an element with the text: /Welcome shell/gi. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

this is my test case

app.spec.tsx

it('should have a greeting as the title', () => {

    const { getByText } = render(

      <Provider store={store}>

      <BrowserRouter>

        <App />

      </BrowserRouter>

      </Provider>

    );

    expect(getByText(/Welcome shell/gi)).toBeTruthy();

  });

what's the error in getByText? Can someone help me?


问:
input of inputfield in unity becomes null when executed for pun2
basically, I am trying to display input of inputfield on the instantiated photon object using photon.rpc . However, input of inputfield does not even write anything on the console. Here is my solution

```<code>// ----------------------------------------------------------------------------
// <copyright file="CharacterInstantiation.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Class that handles character instantiation when the actor is joined.
// It adds multiple prefabs support to OnJoinedInstantiate.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------

namespace ExitGames.Demos.DemoPunVoice
{
    using UnityEngine;

    public class CharacterInstantiation : OnJoinedInstantiate
    {
        TextMesh output;
        PhotonView photonView;
        int i = 0;

        public delegate void OnCharacterInstantiated(GameObject character);

        public static event OnCharacterInstantiated CharacterInstantiated;

        public new void OnJoinedRoom()
        {
            if (this.PrefabsToInstantiate != null)
            {
                GameObject o = PrefabsToInstantiate[(PhotonNetwork.player.ID - 1) % 4];
                Debug.Log("Instantiating: " + o.name);
                Vector3 spawnPos = Vector3.zero;

                if (this.SpawnPosition != null)
                {
                    spawnPos = this.SpawnPosition.position;
                }

                Vector3 random = Random.insideUnitSphere;
                random = this.PositionOffset * random.normalized;
                spawnPos += random;
                spawnPos.y = 0;
                Camera.main.transform.position += spawnPos;

                o = PhotonNetwork.Instantiate(o.name, spawnPos, Quaternion.identity, 0);

                if (CharacterInstantiated != null)
                {
                    CharacterInstantiated(o);
                }

                photonView = o.GetPhotonView();
            }
        }

        public void ReadStr(string s)
        {
            Debug.Log(s);
            Debug.Log("readStr" + s);
            photonView.RPC("ReadStringInput", PhotonTargets.All, s);
        }
    }
}
</code>```

and i have a script under each prefab to be instantiated

```<code>using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

public class ReadInput : MonoBehaviour
{
    private string input;

    TextMesh output;

    [PunRPC]
    public void ReadStringInput(string s)
    {
        Debug.Log(s);
        output = GetComponentInChildren<TextMesh>();
        output.text = s;
    }
}
</code>```

There is no other error message and seems to properly call targeted function, but one problem is string input of the inputfield becomes null value, and it displays "" on the console on both functions. I correctly assigned ReadStr on "on End Edit" of inputfield, but it is very frustration that whatever input i put, it becomes a null value. I'd greatly appreciate if anyone helps me with this matter.

Body:
basically, I am trying to display input of inputfield on the instantiated photon object using photon.rpc . However, input of inputfield does not even write anything on the console. Here is my solution

// ----------------------------------------------------------------------------
// <copyright file="CharacterInstantiation.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
//
// Class that handles character instantiation when the actor is joined.
// It adds multiple prefabs support to OnJoinedInstantiate.
//
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------

namespace ExitGames.Demos.DemoPunVoice
{
    using UnityEngine;

    public class CharacterInstantiation : OnJoinedInstantiate
    {
        TextMesh output;
        PhotonView photonView;
        int i = 0;

        public delegate void OnCharacterInstantiated(GameObject character);

        public static event OnCharacterInstantiated CharacterInstantiated;

        public new void OnJoinedRoom()
        {
            if (this.PrefabsToInstantiate != null)
            {
                GameObject o = PrefabsToInstantiate[(PhotonNetwork.player.ID - 1) % 4];
                Debug.Log("Instantiating: " + o.name);
                Vector3 spawnPos = Vector3.zero;

                if (this.SpawnPosition != null)
                {
                    spawnPos = this.SpawnPosition.position;
                }

                Vector3 random = Random.insideUnitSphere;
                random = this.PositionOffset * random.normalized;
                spawnPos += random;
                spawnPos.y = 0;
                Camera.main.transform.position += spawnPos;

                o = PhotonNetwork.Instantiate(o.name, spawnPos, Quaternion.identity, 0);

                if (CharacterInstantiated != null)
                {
                    CharacterInstantiated(o);
                }

                photonView = o.GetPhotonView();
            }
        }

        public void ReadStr(string s)
        {
            Debug.Log(s);
            Debug.Log("readStr" + s);
            photonView.RPC("ReadStringInput", PhotonTargets.All, s);
        }
    }
}

and i have a script under each prefab to be instantiated

using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

public class ReadInput : MonoBehaviour
{
    private string input;

    TextMesh output;

    [PunRPC]
    public void ReadStringInput(string s)
    {
        Debug.Log(s);
        output = GetComponentInChildren<TextMesh>();
        output.text = s;
    }
}

There is no other error message and seems to properly call targeted function, but one problem is string input of the inputfield becomes null value, and it displays "" on the console on both functions. I correctly assigned ReadStr on "on End Edit" of inputfield, but it is very frustration that whatever input i put, it becomes a null value. I'd greatly appreciate if anyone helps me with this matter.


问:
is it possible to convert a string to number in DynamoDb PartiQL
I am using the below query where minDaysToDeparture and maxDaysToDeparture are string but I have to put in the where block with comparison operators.

I have tried the below queries (not working):

```<code>SELECT *
FROM Rules
WHERE  (
AND (  minDaysToDeparture<='8' )
AND (  maxDaysToDeparture>='8' )
AND status = '1' )

SELECT *
FROM Rules
WHERE  (
AND (  '5'<='8' )
AND (  '10'>='8' )
AND status = '1' )
</code>```

The below query works, but somehow I cannot change type of '8' it has to remain string. But if there is any toNumber method then I can use it without any issue.

```<code>SELECT *
FROM Rules
WHERE  (
AND (  5<=8 )
AND (  10>=8 )
AND status = '1' )
</code>```

Looking forward to your help.

Thanks!

Body:
I am using the below query where minDaysToDeparture and maxDaysToDeparture are string but I have to put in the where block with comparison operators.

I have tried the below queries (not working):

SELECT *
FROM Rules
WHERE  (
AND (  minDaysToDeparture<='8' )
AND (  maxDaysToDeparture>='8' )
AND status = '1' )

SELECT *
FROM Rules
WHERE  (
AND (  '5'<='8' )
AND (  '10'>='8' )
AND status = '1' )

The below query works, but somehow I cannot change type of '8' it has to remain string. But if there is any toNumber method then I can use it without any issue.

SELECT *
FROM Rules
WHERE  (
AND (  5<=8 )
AND (  10>=8 )
AND status = '1' )

Looking forward to your help.

Thanks!


问:
tf objectection api: how to export saved model to onnx without postprocess (NMS)?
I need to remove postprocess part from the model trained with Tensorflow Objection Detection API (SSD Arch). How can I do it?</p>


问:
Unable to run the app, it launches and immediately terminates
The steps invole:

Open VS code as administrator.

yarn clean:android to clean the project

yarn android

It does the configuration and installs the app in my phone, but the moment the app launches in my phone, it terminates and there is no error shown in the terminal. [This is the error it shows on my phone](https://i.stack.imgur.com/IIEM6.png)

I tried to clean the app and the modules. The app is working in my other colleuges phones with the same configurations.
I was expecting it would work in my phone as well for testing purposes.


问:
Cascader component
```<code>import React from 'react';
    import './index.css';
    import { Cascader } from 'antd';

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

const options: Option[] = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake',
          },
        ],
      },
    ],
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
          },
        ],
      },
    ],
  },
];

const onChange = (value: string[]) => {
  console.log(value);
};

const App: React.FC = () => (
  <Cascader options={options} onChange={onChange} placeholder="Please select" />
);

export default App;
</code>```

This is my Cascader.tsx

```<code>import { Icon } from "@font-awesome";
import { Input, Menu, Popover } from "@mantine/core";

import { CascaderIterator } from "./cascaderIterator";

interface CascaderProps {
  options: Option[];
  onChange(value: string[]): void;
}
interface Option {
  value: string;
  label: string;
  children?: Option[];
}

export const Cascader = ({ options }: CascaderProps) => {
  return (
    <Menu position="bottom-start" closeOnItemClick={false}>
      <Menu.Target>
        <Input style={{ width: "50%" }} />
      </Menu.Target>
      <Menu.Dropdown
        styles={{
          root: {
            width: "94px",
          },
        }}
      >
        {options.map((data) => (
          <Popover key={data.value} position="right">
            <Popover.Target>
              <Menu.Item rightSection={data.children ? <Icon icon="chevron-right"></Icon> : null} key={data.value}>
                {data.label}
              </Menu.Item>
            </Popover.Target>
            <Popover.Dropdown p={0}>
              {data.children?.map((c) => {
                return (
                  <Menu.Item rightSection={c.children ? <Icon icon="chevron-right"></Icon> : null} key={c.value}>
                    <CascaderIterator options={c.children} label={c.label} />
                  </Menu.Item>
                );
              })}
            </Popover.Dropdown>
          </Popover>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};
</code>```

This is my CascaderIterator.tsx

```<code>import { Menu, Popover } from "@mantine/core";
interface CascaderIteratorProps {
  options?: Option[];
  label: string;
}
interface Option {
  value: string;
  label: string;
  children?: Option[];
}

export const CascaderIterator = ({ options, label }: CascaderIteratorProps) => {
  return (
    <Menu position="right" closeOnItemClick={false}>
      <Menu.Target>
        <Menu.Item>{label}</Menu.Item>
      </Menu.Target>
      <Menu.Dropdown>
        {options?.map((data) => (
          <Popover key={data.value} position="right">
            <Popover.Target>
              <Menu.Item rightSection={data.children ? <Icon icon="chevron-right"></Icon> : null} key={data.value}>
                {data.label}
              </Menu.Item>
            </Popover.Target>

            <Popover.Dropdown p={0}>
              {data.children?.map((c) => (
                <Menu.Item rightSection={c.children ? <Icon icon="chevron-right"></Icon> : null} key={c.value}>
                  <CascaderIterator options={c.children} key={c.value} label={c.label} />
                </Menu.Item>
              ))}
            </Popover.Dropdown>
          </Popover>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};
</code>```

I want cascader component without using antd package. instead of that i want to use mantine core if it is possible how can i do that? Here I have taken two components cascder.tsx and cascaderiterator.tsx to iterate children component but it is not selecting in input box like antd cascader will do and not closing after last child. How can solve that where excatly runs like antd cascader please show me better way to do that.

Title: Cascader component

Body:
import React from 'react';
    import './index.css';
    import { Cascader } from 'antd';

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

const options: Option[] = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake',
          },
        ],
      },
    ],
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
          },
        ],
      },
    ],
  },
];

const onChange = (value: string[]) => {
  console.log(value);
};

const App: React.FC = () => (
  <Cascader options={options} onChange={onChange} placeholder="Please select" />
);

export default App;

This is my Cascader.tsx

import { Icon } from "@font-awesome";
import { Input, Menu, Popover } from "@mantine/core";

import { CascaderIterator } from "./cascaderIterator";

interface CascaderProps {
  options: Option[];
  onChange(value: string[]): void;
}
interface Option {
  value: string;
  label: string;
  children?: Option[];
}

export const Cascader = ({ options }: CascaderProps) => {
  return (
    <Menu position="bottom-start" closeOnItemClick={false}>
      <Menu.Target>
        <Input style={{ width: "50%" }} />
      </Menu.Target>
      <Menu.Dropdown
        styles={{
          root: {
            width: "94px",
          },
        }}
      >
        {options.map((data) => (
          <Popover key={data.value} position="right">
            <Popover.Target>
              <Menu.Item rightSection={data.children ? <Icon icon="chevron-right"></Icon> : null} key={data.value}>
                {data.label}
              </Menu.Item>
            </Popover.Target>
            <Popover.Dropdown p={0}>
              {data.children?.map((c) => {
                return (
                  <Menu.Item rightSection={c.children ? <Icon icon="chevron-right"></Icon> : null} key={c.value}>
                    <CascaderIterator options={c.children} label={c.label} />
                  </Menu.Item>
                );
              })}
            </Popover.Dropdown>
          </Popover>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};

This is my CascaderIterator.tsx

import { Menu, Popover } from "@mantine/core";
interface CascaderIteratorProps {
  options?: Option[];
  label: string;
}
interface Option {
  value: string;
  label: string;
  children?: Option[];
}

export const CascaderIterator = ({ options, label }: CascaderIteratorProps) => {
  return (
    <Menu position="right" closeOnItemClick={false}>
      <Menu.Target>
        <Menu.Item>{label}</Menu.Item>
      </Menu.Target>
      <Menu.Dropdown>
        {options?.map((data) => (
          <Popover key={data.value} position="right">
            <Popover.Target>
              <Menu.Item rightSection={data.children ? <Icon icon="chevron-right"></Icon> : null} key={data.value}>
                {data.label}
              </Menu.Item>
            </Popover.Target>

            <Popover.Dropdown p={0}>
              {data.children?.map((c) => (
                <Menu.Item rightSection={c.children ? <Icon icon="chevron-right"></Icon> : null} key={c.value}>
                  <CascaderIterator options={c.children} key={c.value} label={c.label} />
                </Menu.Item>
              ))}
            </Popover.Dropdown>
          </Popover>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};

I want cascader component without using antd package. instead of that i want to use mantine core if it is possible how can i do that? Here I have taken two components cascder.tsx and cascaderiterator.tsx to iterate children component but it is not selecting in input box like antd cascader will do and not closing after last child. How can solve that where excatly runs like antd cascader please show me better way to do that.


问:
Create an automatic status change for room booking in Spreadshee
Trying to set up a Google Sheet that can automatically determine request status based on previous request.

So the flow start with Zapier pushing information to this sheet and specific row
Data Entry Sheet
*The data here will be replaced every time there is a new booking request so the number of cell will always be the same.

The approval system that is needed use the "first come first serve" rule where as long as there is no previous request that match the time within the request, google sheet can directly says it's approved, otherwise it is rejected.

The problem is we need to know if there is already another approved request that is submitted before the request that we want to check. This is the sheet we use to track all previous request
Sheet of Previous Request

Is there any way we can compare the data from "New Request" Sheet to all of previous request in "Reservation" Sheet?

Also another question, can we add all the the request that came in into the list of previous request?

Thank You!

Basically I haven't tried any combinations of command but I have try using filter or array individually but it doesn't work.

This is a new project so there is no previous result I can show but the expected result is all the request will have their request status filled so Zapier can return that request status to it's requestor.


问:
When to use c++ module?
This question might be too broad but it really tickled my mind lately:

I recently found out about modules in modern C++ : https://en.cppreference.com/w/cpp/language/modules

But I really don't get their purpose and when to use it instead of namespaces or just library headers?

In the example provided they now use import <iostream>; instead of include <iostream>;, what is the the difference in using one versus the other? Which one is to be preferred?

They say that "module are orthogonal to namespaces"? What does this mean?

What are the guidelines regarding development, should we now avoid headers and stuff ?

For instance:

helloworld.cpp

```<code>export module helloworld; // module declaration

import <iostream>;        // import declaration

export void hello()       // export declaration
{
    std::cout << "Hello world!\n";
}
</code>```

main.cpp

```<code>import helloworld; // import declaration

int main()
{
    hello();
}
</code>```

VERSUS

helloworld.h / helloworld.cpp

```<code>include <iostream>;

namespace ns
{
    void hello();
}

#include "helloworld.h";

void ns::hello()
{
    std::cout << "Hello world!\n";
}
</code>```

main.cpp

```<code>#include "helloworld.h";

int main()
{
    ns::hello(); // optionally "using namespace ns; to avoid ns::"
}
</code>```

Title: When to use c++ module?

Body:
This question might be too broad but it really tickled my mind lately:

I recently found out about modules in modern C++ : https://en.cppreference.com/w/cpp/language/modules

But I really don't get their purpose and when to use it instead of namespaces or just library headers?

In the example provided they now use import <iostream>; instead of include <iostream>;, what is the the difference in using one versus the other? Which one is to be preferred?

They say that "module are orthogonal to namespaces"? What does this mean?

What are the guidelines regarding development, should we now avoid headers and stuff ?

For instance:

helloworld.cpp

export module helloworld; // module declaration

import <iostream>;        // import declaration

export void hello()       // export declaration
{
    std::cout << "Hello world!\n";
}

main.cpp

import helloworld; // import declaration

int main()
{
    hello();
}

VERSUS

helloworld.h / helloworld.cpp

include <iostream>;

namespace ns
{
    void hello();
}

#include "helloworld.h";

void ns::hello()
{
    std::cout << "Hello world!\n";
}

main.cpp

#include "helloworld.h";

int main()
{
    ns::hello(); // optionally "using namespace ns; to avoid ns::"
}


问:
how can I disable windows micphone enhancement by c++ code?
is there a way to disable the microphone audio enhancements from C++ code?

We are doing some audio processing things on the incoming microphone signal, and the microphone enhancements cause all kinds of trouble. We know we can turn it off manually on Windows10 by going to the Control panel --> Sound --> Recording --> Microphone --> Properties --> advanced--> Enhancements, but we need a way to do this from code.

enter image description here

when I try to access it via C++ It comes back saying there is no AGC on the device.

void AudioDeviceWindowsCore::DisableHardwareAGC() {
  // get device topology object for that endpoint
  CComPtr<IDeviceTopology> pTopo = NULL;
  HRESULT ret = _ptrDeviceIn->Activate(__uuidof(IDeviceTopology), CLSCTX_ALL, NULL,
                               (void**)&pTopo);
  if (FAILED(ret)) {
    RTC_LOG(LS_ERROR) << "Couldn't get device topology object: hr = 0x"
                      << rtc::ToHex(ret);
  } else {
    UINT count = 0;
    pTopo->GetConnectorCount(&count);

    CComPtr<IConnector> pConn = NULL;
    ret = pTopo->GetConnector(0, &pConn);
    if (FAILED(ret)) {
      RTC_LOG(LS_ERROR) << __FUNCTION__ << " GetConnector:" << rtc::ToHex(ret);
      return ;
    }
    CComPtr<IConnector> pConnNext = NULL;
    ret = pConn->GetConnectedTo(&pConnNext);
    if (FAILED(ret)) {
      RTC_LOG(LS_ERROR) << __FUNCTION__
                        << " GetConnectedTo:" << rtc::ToHex(ret);
      return ;
    }
    CComPtr<IPart> pPart = NULL;
    const IID IID_IPart = __uuidof(IPart);
    ret = pConnNext->QueryInterface(IID_IPart, (void**)&pPart);
    if (FAILED(ret)) {
      RTC_LOG(LS_ERROR) << __FUNCTION__
                        << " QueryInterface:" << rtc::ToHex(ret);
      return ;
    }

    // all the real work is done in this function
    ret = WalkTreeForwardsFromPart(pPart);

    if (SUCCEEDED(ret)) {
      RTC_LOG(INFO) << " now close hardware AGC ret:" << rtc::ToHex(ret);
    } else {
      RTC_LOG(INFO) << " Hardware not Supports Microphone AGC";
    }
  }
}

HRESULT WalkTreeForwardsFromPart(IPart* pPart) {
  HRESULT hr = S_OK;

  LPWSTR pwszPartName = NULL;
  hr = pPart->GetName(&pwszPartName);
  if (FAILED(hr)) {
    RTC_LOG(LS_ERROR) << "Could not get part name: hr = 0x"<<rtc::ToHex(hr);
    return hr;
  }
  RTC_LOG(INFO) << "Part name: " << *pwszPartName ? pwszPartName : L"Unnamed";
  CoTaskMemFree(pwszPartName);
  GUID type_id;
  hr = pPart->GetSubType(&type_id);
  if (hr == S_OK){
    if (IsEqualGUID(type_id,KSNODETYPE_LOUDNESS) ) {
      const IID IID_IAudioLoudness = __uuidof(IAudioLoudness);
      IAudioLoudness* loudness = NULL;
      hr = pPart->Activate(CLSCTX_ALL, IID_IAudioLoudness, (void**)&loudness);
      if (E_NOINTERFACE == hr) {
        RTC_LOG(LS_ERROR) << "NO AudioLoudness CONTROL";
        // not a Microphone node
      } else if (FAILED(hr)) {
        RTC_LOG(LS_ERROR) << "Unexpected failure trying to activate "
                             "IID_IAudioLoudness : hr = 0x"
                          << rtc::ToHex(hr);
      } else {
        // it's an AGC node...
        RTC_LOG(INFO) << "HAS IAudioLoudness CONTROL";
        hr = loudness->SetEnabled(0, NULL);

        if (FAILED(hr)) {
          RTC_LOG(LS_ERROR)
              << "AudioLoudness Failed: hr = 0x" << rtc::ToHex(hr);
          loudness->Release();
          return hr;
        }

        loudness->Release();
      }
    } else if (IsEqualGUID(type_id, KSNODETYPE_AGC)) {
      // Check AGC settings
      const IID IID_IAudioAutoGainControl = __uuidof(IAudioAutoGainControl);

      IAudioAutoGainControl* aGCcontrol = NULL;
      hr = pPart->Activate(CLSCTX_ALL, IID_IAudioAutoGainControl,
                           (void**)&aGCcontrol);
      if (E_NOINTERFACE == hr) {
        RTC_LOG(LS_ERROR) << "NO AGC CONTROL";
        // not a Microphone node
      } else if (FAILED(hr)) {
        RTC_LOG(LS_ERROR) << "Unexpected failure trying to activate "
                             "IAudioAutoGainControl : hr = 0x"
                          << rtc::ToHex(hr);
        return hr;
      } else {
        // it's an AGC node...
        RTC_LOG(INFO) << "HAS AGC CONTROL";
        aGCcontrol->SetEnabled(0, NULL);

        if (FAILED(hr)) {
          RTC_LOG(LS_ERROR) << "AGC Failed: hr = 0x" << rtc::ToHex(hr);
          aGCcontrol->Release();
          return hr;
        }
        aGCcontrol->Release();
      }
    }
  }

  // get the list of incoming parts
  IPartsList* pOutgoingParts = NULL;
  hr = pPart->EnumPartsOutgoing(&pOutgoingParts);

  if (E_NOTFOUND == hr) {
    // not an error... we've just reached the end of the path
    RTC_LOG(INFO) << "No incoming parts at this part";
    return hr;
  }
  if (FAILED(hr)) {
    RTC_LOG(LS_ERROR) << " Couldn't enum outgoing parts";
    return hr;
  }
  UINT nParts = 0;
  hr = pOutgoingParts->GetCount(&nParts);
  if (FAILED(hr)) {
    RTC_LOG(LS_ERROR) << "Couldn't get count of outgoing parts";
    pOutgoingParts->Release();
    return hr;
  }

  // walk the tree on each incoming part recursively
  for (UINT n = 0; n < nParts; n++) {
    IPart* pOutgoingPart = NULL;
    hr = pOutgoingParts->GetPart(n, &pOutgoingPart);
    if (FAILED(hr)) {
      RTC_LOG(LS_ERROR) << "Couldn't get part ";
      pOutgoingParts->Release();
      return hr;
    }

    hr = WalkTreeForwardsFromPart(pOutgoingPart);
    if (FAILED(hr)) {
      RTC_LOG(LS_ERROR) << " Couldn't walk tree on part";
      pOutgoingPart->Release();
      pOutgoingParts->Release();
      return hr;
    }
    pOutgoingPart->Release();
  }

  pOutgoingParts->Release();

  return S_OK;
}
```


问:
How can I detect if picked video is 4K?
Is it possible to check if picked video is 4K in React Native?
I don't want users to be able to upload 4K videos, so how I can handle this?

Im using react-native-image-crop-picker.

Title: How can I detect if picked video is 4K?


问:
How to reorder section in Tableview
I want to reorder section and row. So by default, native section reordering is not possible. So I implemented the section as a row. And reorder section and row. But the problem is when I reorder the section then it takes a row. It will crash the application.

Can you please help me?

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). Table view: <UITableView: 0x7f874f026000; frame = (0 59; 393 759); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x6000023bde60>; backgroundColor = <UIDynamicSystemColor: 0x60000388b640; name = tableBackgroundColor>; layer = <CALayer: 0x600002df4c60>; contentOffset: {0, 0}; contentSize: {393, 206.66667175292969}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <ReorderTableView.ViewController: 0x7f874c709840>>

```<code>class ViewController: UIViewController {

    @IBOutlet weak var tblView: UITableView!

    var arrSection = [Section]()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        tblView.isEditing = true
        tblView.dataSource = self
        tblView.delegate = self
        // register tableviewcell
        tblView.register(UINib(nibName:"SectionTableViewCell", bundle: nil), forCellReuseIdentifier: "SectionTableViewCell")
        setupView()
    }

    func setupView(){
        let obj = Group(groupName: "Group1")
        let sec = Section(sectionName: "Section1", group: [obj])
        let sec1 = Section(sectionName: "Section2", group: [obj])
        arrSection.append(sec)
        arrSection.append(sec1)
        tblView.reloadData()
    }
}

extension ViewController : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return arrSection.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if arrSection[section].group?.count ?? 0 > 0 {
            let temp = arrSection[section].group?.count ?? 0
            return temp + 1
        }
        else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let obj = arrSection[indexPath.section]
            let cell = tableView.dequeueReusableCell(withIdentifier: "SectionTableViewCell") as! SectionTableViewCell
            cell.lblTitle.text = obj.sectionName
            return cell
        }
        else{
            let obj = arrSection[indexPath.section].group?[indexPath.row - 1]
            let cell = tableView.dequeueReusableCell(withIdentifier: "SectionTableViewCell") as! SectionTableViewCell
            cell.lblTitle.text = obj?.groupName ?? ""
            return cell
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return UITableView.automaticDimension
        }else{
            return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        tblView.beginUpdates()
        let movingItem = self.arrSection[sourceIndexPath.section]
        self.arrSection.remove(at: sourceIndexPath.section)
        self.arrSection.insert(movingItem, at: destinationIndexPath.section)
        tblView.moveSection(sourceIndexPath.section, toSection: destinationIndexPath.section)
        tblView.endUpdates()
    }
}
</code>```

Title: How to reorder section in Tableview

Body:
I want to reorder section and row. So by default, native section reordering is not possible. So I implemented the section as a row. And reorder section and row. But the problem is when I reorder the section then it takes a row. It will crash the application.

Can you please help me?

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). Table view: <UITableView: 0x7f874f026000; frame = (0 59; 393 759); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x6000023bde60>; backgroundColor = <UIDynamicSystemColor: 0x60000388b640; name = tableBackgroundColor>; layer = <CALayer: 0x600002df4c60>; contentOffset: {0, 0}; contentSize: {393, 206.66667175292969}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <ReorderTableView.ViewController: 0x7f874c709840>>

class ViewController: UIViewController {

    @IBOutlet weak var tblView: UITableView!

    var arrSection = [Section]()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        tblView.isEditing = true
        tblView.dataSource = self
        tblView.delegate = self
        // register tableviewcell
        tblView.register(UINib(nibName:"SectionTableViewCell", bundle: nil), forCellReuseIdentifier: "SectionTableViewCell")
        setupView()
    }

    func setupView(){
        let obj = Group(groupName: "Group1")
        let sec = Section(sectionName: "Section1", group: [obj])
        let sec1 = Section(sectionName: "Section2", group: [obj])
        arrSection.append(sec)
        arrSection.append(sec1)
        tblView.reloadData()
    }
}

extension ViewController : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return arrSection.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if arrSection[section].group?.count ?? 0 > 0 {
            let temp = arrSection[section].group?.count ?? 0
            return temp + 1
        }
        else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let obj = arrSection[indexPath.section]
            let cell = tableView.dequeueReusableCell(withIdentifier: "SectionTableViewCell") as! SectionTableViewCell
            cell.lblTitle.text = obj.sectionName
            return cell
        }
        else{
            let obj = arrSection[indexPath.section].group?[indexPath.row - 1]
            let cell = tableView.dequeueReusableCell(withIdentifier: "SectionTableViewCell") as! SectionTableViewCell
            cell.lblTitle.text = obj?.groupName ?? ""
            return cell
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return UITableView.automaticDimension
        }else{
            return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        tblView.beginUpdates()
        let movingItem = self.arrSection[sourceIndexPath.section]
        self.arrSection.remove(at: sourceIndexPath.section)
        self.arrSection.insert(movingItem, at: destinationIndexPath.section)
        tblView.moveSection(sourceIndexPath.section, toSection: destinationIndexPath.section)
        tblView.endUpdates()
    }
}


问:
Eclipse & Angular & Eslint: warnings in HTML files 'Unknown tag'
I have in my HTML file e.g.

```<code><p>
    <input (change)="onFileChange($event)" type="file" multiple="false" />
    Loaded file '{{ fileName }}'
</p>
</code>```

which is linted as

I have my Angular project in a workspace together with another Angular project. Their the Eslint works find and doesn't complain about the unknown tags/attributes. The sample is a simplified one since also not my own created components are recognized nor Angular Material tags.

I've checked the .project setting files and the package.json both are quite similar. I suspect the tsconfig.json but I'm not sure if that's the root cause of my problem.

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "suppressImplicitAnyIndexErrors": true,
    "skipLibCheck": true,
    "noImplicitAny": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "useUnknownInCatchVariables": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}
</code>```

Any idea what to check and from where the eslint config is used?

Body:
I have in my HTML file e.g.

    <input (change)="onFileChange($event)" type="file" multiple="false" />
    Loaded file '{{ fileName }}'

which is linted as

I have my Angular project in a workspace together with another Angular project. Their the Eslint works find and doesn't complain about the unknown tags/attributes. The sample is a simplified one since also not my own created components are recognized nor Angular Material tags.

I've checked the .project setting files and the package.json both are quite similar. I suspect the tsconfig.json but I'm not sure if that's the root cause of my problem.

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "suppressImplicitAnyIndexErrors": true,
    "skipLibCheck": true,
    "noImplicitAny": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "useUnknownInCatchVariables": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Any idea what to check and from where the eslint config is used?


问:
Fixed a Zip Path Traversal Vulnerability in Android app ,but Google Play still issued a warning
I have some apps on google play, and they are all prompted that there is an unsafe unzip mode. After I fixed this problem with the same code, most of my APPs no longer have warnings, but one APP still has warnings. I don't know what the problem is.

```<code>public static boolean unZipFile(String unZipPath, String zipPath) {
        unZipPath = createSeparator(unZipPath);
        BufferedOutputStream bos = null;
        ZipInputStream zis = null;

        boolean result = false;

        try {
            String filename;
            zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipPath)));
            ZipEntry ze;
            byte[] buffer = new byte[BUFF_SIZE];
            int count;

            while ((ze = zis.getNextEntry()) != null) {
                filename = ze.getName();

                //zip fix
                File zeFile = new File(unZipPath, filename);
                String zePath = zeFile.getCanonicalPath();
                File targetFile = new File(unZipPath);
                String targetPath = targetFile.getCanonicalPath();
                if (!TextUtilsEx.startsWith(zePath, targetPath + File.separator)) {
                    throw new ZipException("Illegal name: " + filename);
                }

                Logger.d(TAG, "ze.getName() = " + filename);
                createSubFolders(filename, unZipPath);
                if (ze.isDirectory()) {
                    File fmd = new File(unZipPath + filename);
                    fmd.mkdirs();
                    continue;
                }
                Logger.d(TAG, "unzip file = " + unZipPath + filename);

                bos = new BufferedOutputStream(new FileOutputStream(unZipPath + filename));
                while ((count = zis.read(buffer)) != -1) {
                    bos.write(buffer, 0, count);
                }
                bos.flush();
                bos.close();
            }
            result = true;
        } catch (Throwable e) {
            Logger.e(TAG, e);
        } finally {
            try {
                if (zis != null) {
                    zis.closeEntry();
                    zis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Throwable e) {
                Logger.e(TAG, e);
            }
        }
        return result;
    }
</code>```

I try to use the modified scheme in this document.

https://support.google.com/faqs/answer/9294009

I used the exception zip file to test, and I can indeed verify that the fix works.

Body:
I have some apps on google play, and they are all prompted that there is an unsafe unzip mode. After I fixed this problem with the same code, most of my APPs no longer have warnings, but one APP still has warnings. I don't know what the problem is.

public static boolean unZipFile(String unZipPath, String zipPath) {
        unZipPath = createSeparator(unZipPath);
        BufferedOutputStream bos = null;
        ZipInputStream zis = null;

        boolean result = false;

        try {
            String filename;
            zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipPath)));
            ZipEntry ze;
            byte[] buffer = new byte[BUFF_SIZE];
            int count;

            while ((ze = zis.getNextEntry()) != null) {
                filename = ze.getName();

                //zip fix
                File zeFile = new File(unZipPath, filename);
                String zePath = zeFile.getCanonicalPath();
                File targetFile = new File(unZipPath);
                String targetPath = targetFile.getCanonicalPath();
                if (!TextUtilsEx.startsWith(zePath, targetPath + File.separator)) {
                    throw new ZipException("Illegal name: " + filename);
                }

                Logger.d(TAG, "ze.getName() = " + filename);
                createSubFolders(filename, unZipPath);
                if (ze.isDirectory()) {
                    File fmd = new File(unZipPath + filename);
                    fmd.mkdirs();
                    continue;
                }
                Logger.d(TAG, "unzip file = " + unZipPath + filename);

                bos = new BufferedOutputStream(new FileOutputStream(unZipPath + filename));
                while ((count = zis.read(buffer)) != -1) {
                    bos.write(buffer, 0, count);
                }
                bos.flush();
                bos.close();
            }
            result = true;
        } catch (Throwable e) {
            Logger.e(TAG, e);
        } finally {
            try {
                if (zis != null) {
                    zis.closeEntry();
                    zis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Throwable e) {
                Logger.e(TAG, e);
            }
        }
        return result;
    }

I try to use the modified scheme in this document.

https://support.google.com/faqs/answer/9294009

I used the exception zip file to test, and I can indeed verify that the fix works.


问:
while validating date label and border bottom red color is not showing , yup validation
color is not showing while validating

label color is not showing while validating for dropdown

im expecting that red color should be shown while validating
for datepicker label, border bottom and dropdown label

// DROPDOWN FIELD
this id dropdown field

```<code><FormInputDropdown
              name='typeId'
              type='text'
              control={control}
              options={TypeData}
              label='Type'
              helperText={errors?.typeId?.message}
              errors={!!errors.typeId}
              register={register('typeId', {
                onChange: (e) => dispatch(setTypeId(e.target.value)),
              })}
            />
</code>```

// DATE FIELD
this id date field

```<code><FormInputDate
              name='acquired'
              control={control}
              label='Date Acquired'
              maxDate={defaultValue.verified}
              helperText={errors?.acquired?.message}
              errors={!!errors.acquired}
              register={register('acquired', {
                onChange: (e) => dispatch(setAcquired(e.target.value)),
              })}
            />
</code>```

// YUP VALIDATION
this is yup validation code

```<code>const input_schema = yup.object().shape({
  assetTag: yup
    .string()
    .max(128, requiredLimit)
    .required(requiredField)
    .nullable(),
  typeId: yup.string().required(requiredField).nullable(),
  manu: yup.string().max(128, requiredLimit).required(requiredField),
  model: yup.string().max(128, requiredLimit).required(requiredField),
  locationId: yup.string().required(requiredField),
  fundingId: yup.string().required(requiredField),
  buildingId: yup.string().required(requiredField),
  serial: yup.string().max(128, requiredLimit).required(requiredField),
  acquired: yup.date().required().typeError(requiredField),
  verified: yup.date().required().typeError(requiredField),
});
</code>```
```<code>const useFunction = useForm({
    mode: 'onChange',
    defaultValues: defaultValue,
    resolver: yupResolver(input_schema),
  });
</code>```

Body:
color is not showing while validating

label color is not showing while validating for dropdown

im expecting that red color should be shown while validating
for datepicker label, border bottom and dropdown label

// DROPDOWN FIELD
this id dropdown field

<FormInputDropdown
              name='typeId'
              type='text'
              control={control}
              options={TypeData}
              label='Type'
              helperText={errors?.typeId?.message}
              errors={!!errors.typeId}
              register={register('typeId', {
                onChange: (e) => dispatch(setTypeId(e.target.value)),
              })}
            />

// DATE FIELD
this id date field

<FormInputDate
              name='acquired'
              control={control}
              label='Date Acquired'
              maxDate={defaultValue.verified}
              helperText={errors?.acquired?.message}
              errors={!!errors.acquired}
              register={register('acquired', {
                onChange: (e) => dispatch(setAcquired(e.target.value)),
              })}
            />

// YUP VALIDATION
this is yup validation code

const input_schema = yup.object().shape({
  assetTag: yup
    .string()
    .max(128, requiredLimit)
    .required(requiredField)
    .nullable(),
  typeId: yup.string().required(requiredField).nullable(),
  manu: yup.string().max(128, requiredLimit).required(requiredField),
  model: yup.string().max(128, requiredLimit).required(requiredField),
  locationId: yup.string().required(requiredField),
  fundingId: yup.string().required(requiredField),
  buildingId: yup.string().required(requiredField),
  serial: yup.string().max(128, requiredLimit).required(requiredField),
  acquired: yup.date().required().typeError(requiredField),
  verified: yup.date().required().typeError(requiredField),
});

const useFunction = useForm({
    mode: 'onChange',
    defaultValues: defaultValue,
    resolver: yupResolver(input_schema),
  });


问:
integrate a jupyter lab editor in React.js
im trying to create an online editor with react.js that looks like jupyter lab: i want to build the cells, the toolbar etc.
I dont need the functionalities (like running a ipynb file), just the UI

how can i use jupterlab editor as a component / how to integrate it?
are there any extentions that could be used / sample apps already made?


问:
Passing the value of property from form and store in variable to do join in LINQ using that variable
I am taking the input from user and store in variable. then I am selecting the data from database using LINQ to do that I have to perform a join condition and the property of that join should change according to what user enter if user select location then it should be e.Location and if he select department it should be e.department . the join condition both the side is a INT and while storing the data in variable I am getting the value in string, for example user select location so the variable is string variable , so on join it should be changed to INT to perform proper join.
In my model class I have 4 property location, department, designation, Etiolation. from front end user select any of this so it should do store in variable then it fetch value from database I have written the below query. it should join with other table to fetch value so this is a case, if user select any of this it should be join with other table for that I want to use variable to join the table .

before making the value change according to user select .

```<code>var param = form["Category"];
var query =  (from e in table1 join c in table2 on e.location equals c.Id select e);
</code>```

doing some thing with the query data

and how I want it to be ,

```<code>var param = form["Category"];
var query =  (from e in table1 join c in table2 on e.param equals c.Id select e);
</code>```

Body:
I am taking the input from user and store in variable. then I am selecting the data from database using LINQ to do that I have to perform a join condition and the property of that join should change according to what user enter if user select location then it should be e.Location and if he select department it should be e.department . the join condition both the side is a INT and while storing the data in variable I am getting the value in string, for example user select location so the variable is string variable , so on join it should be changed to INT to perform proper join.
In my model class I have 4 property location, department, designation, Etiolation. from front end user select any of this so it should do store in variable then it fetch value from database I have written the below query. it should join with other table to fetch value so this is a case, if user select any of this it should be join with other table for that I want to use variable to join the table .

before making the value change according to user select .

var param = form["Category"];
var query =  (from e in table1 join c in table2 on e.location equals c.Id select e);

doing some thing with the query data

and how I want it to be ,

var param = form["Category"];
var query =  (from e in table1 join c in table2 on e.param equals c.Id select e);


问:
Random SQLiteDatabaseLockedException
I am receiving this crash in firebase:

Fatal Exception:
android.database.sqlite.SQLiteDatabaseLockedException: database is
locked (Sqlite code 5), (OS error - 11:Try again)        at
android.database.sqlite.SQLiteConnection.nativeExecute(SQLiteConnection.java)
at
android.database.sqlite.SQLiteConnection.execute(SQLiteConnection.java:591)
at
android.database.sqlite.SQLiteSession.beginTransactionUnchecked(SQLiteSession.java:332)
at
android.database.sqlite.SQLiteSession.beginTransaction(SQLiteSession.java:311)
at
android.database.sqlite.SQLiteDatabase.beginTransaction(SQLiteDatabase.java:532)
at
android.database.sqlite.SQLiteDatabase.beginTransactionNonExclusive(SQLiteDatabase.java:467)
at
androidx.sqlite.db.framework.FrameworkSQLiteDatabase.beginTransactionNonExclusive(FrameworkSQLiteDatabase.java:78)
at
androidx.room.RoomDatabase.internalBeginTransaction(RoomDatabase.java:570)
at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:555)
at
androidx.work.impl.utils.StopWorkRunnable.run(StopWorkRunnable.java:56)
at
androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:776)

I am never catch it during the development process, but I am receiving it from Firebase Crashlytics, looks like it kind of random. For database I am using room. Is there any chance that I can fix it by myself?

Seems like the only thing that I am able to do - to update room version, but it does not help. Maybe I need to add some flag to the database.

Title: Random SQLiteDatabaseLockedException


问:
How to make docker container running judge0 use cgroupV1 in ubuntu?
I have installed a online IDE backend architecture Judge0 for a coding web app. I am running a container in docker. The problem is that judge0 works only with cgroupV1 not with cgroupV2. So I am facing a issue here where on running the app I am getting interal error.

On researching judge0 github repo I found the issue is due to cgroupv2 being used by default.

On running command

grep cgroup /proc/mounts

I am getting output as

cgroup2 /sys/fs/cgroup cgroup2
rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot 0 0

I need to change the whole permission to cgroup1 not to cgroup2. Even after running   editing the GRUB_CMDLINE_LINUX line in /etc/default/grub and running

```<code>sudo update-grub
</code>```

I am not able to resolve the issue. Need help on how to change permission to cgroup1 in ubuntu 22.04

Body:
I have installed a online IDE backend architecture Judge0 for a coding web app. I am running a container in docker. The problem is that judge0 works only with cgroupV1 not with cgroupV2. So I am facing a issue here where on running the app I am getting interal error.

On researching judge0 github repo I found the issue is due to cgroupv2 being used by default.

On running command

grep cgroup /proc/mounts

I am getting output as

cgroup2 /sys/fs/cgroup cgroup2
rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot 0 0

I need to change the whole permission to cgroup1 not to cgroup2. Even after running   editing the GRUB_CMDLINE_LINUX line in /etc/default/grub and running

sudo update-grub

I am not able to resolve the issue. Need help on how to change permission to cgroup1 in ubuntu 22.04


问:
Input auto focus not working on mobile browsers on angular app
I developed multiple inputs and after one input filled cursor will auto focus to next input, it's working fine on pc and laptop browsers.

my code:

```<code>document.getElementById(ne)?.focus()
document.getElementById(ne)?.scrollIntoView()
</code>```

.focus() and scrollIntoView() both are not working

Tested devices: Android google chrome

Anyone have solution for this it may helpful.

Body:
I developed multiple inputs and after one input filled cursor will auto focus to next input, it's working fine on pc and laptop browsers.

my code:

document.getElementById(ne)?.focus()
document.getElementById(ne)?.scrollIntoView()

.focus() and scrollIntoView() both are not working

Tested devices: Android google chrome

Anyone have solution for this it may helpful.