问:
Debugger contradicting itself when describing UINavigationController
How is it possible that the navigation controller shown in the screenshot is described in the memory debugger as having 1 children (of type ContactsTableViewController) and at the same time in the lldb prompt is described as having 0 elements?

If you want more context or the code to reproduce it, please look at the code shown in: here

UPDATE:

I haven't run any other commands between the time I captured the memory graph and the time I ran the po command.

The minimal reproducible example is the following playground snippet ( I only have seen this strange behaviour when using a UIViewControllerRepresentable.Coordinator, that's why the minimal example is a bit complex):

```<code>import PlaygroundSupport
import SwiftUI
import UIKit

protocol Coordinator {
    var nav: UINavigationController { get }
    func start()
}

final class FlowCoordinator: Coordinator {
    struct Dependencies {
        let nav: UINavigationController
        let screen1Factory: () -> UIViewController
        let screen2Factory: () -> UIViewController
    }

    var nav: UINavigationController
    let screen1Factory: () -> UIViewController
    let screen2Factory: () -> UIViewController

    init(dependencies: FlowCoordinator.Dependencies) {
        self.nav = dependencies.nav
        self.screen1Factory = dependencies.screen1Factory
        self.screen2Factory = dependencies.screen2Factory
    }

    func start() {
        let vc = screen1Factory() as! ViewController
        vc.flowCoordinator = self
        nav.pushViewController(vc, animated: false)
        print("FlowCoordinator.started: flowCoordinator.nav: ", nav, "VCs count: ", nav.viewControllers.count)
    }

    func screen2() {
        print("Pushing screen2")
        let vc = screen2Factory() as! ViewController
        vc.flowCoordinator = self
        nav.pushViewController(vc, animated: false)
        print("Coordinator.viewController.flowCoordinator.nav: ", "VCs count: ",
              nav.viewControllers.count)
    }
}

final class ViewController: UITableViewController {
    weak var flowCoordinator: FlowCoordinator?

    // Array of cities to display in the table view
    let cities = ["New York", "Paris", "Tokyo"]

    init() {
        super.init(nibName: nil, bundle: nil)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CityCell")
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section
        return cities.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CityCell", for: indexPath)
        // Configure the cell...
        cell.textLabel?.text = cities[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        flowCoordinator?.screen2()
    }
}

final class AppDependencies {
    lazy var flowCoordinator: FlowCoordinator = {
        let navigationController = UINavigationController()
        navigationController.navigationBar.prefersLargeTitles = true
        let flowCoordinatorDependencies = FlowCoordinator.Dependencies(
            nav: navigationController,
            screen1Factory: makeViewController1,
            screen2Factory: makeViewController2)
        return FlowCoordinator(dependencies: flowCoordinatorDependencies)
    }()

    func makeViewController1() -> UIViewController {
        let vc = ViewController()
        vc.title = "View 1"
        return vc
    }

    func makeViewController2() -> UIViewController {
        let vc = ViewController()
        vc.title = "View 2"
        return vc
    }
}
[![enter image description here][1]][1]

struct View1: UIViewControllerRepresentable {
    let flowCoordinator: FlowCoordinator

    func makeUIViewController(context: Context) -> ViewController {
        return context.coordinator.viewController
    }

    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
    }
}

extension View1 {
    final class Coordinator: NSObject, UITableViewDelegate {
        var viewController: ViewController
        var flowCoordinator: FlowCoordinator
        init(flowCoordinator: FlowCoordinator) {
            self.flowCoordinator = flowCoordinator
            self.flowCoordinator.start()
            self.viewController = self.flowCoordinator.nav.viewControllers.first as! ViewController
            super.init()
            viewController.tableView.delegate = self
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("View1.tableView(_:didSelectRowAt:indexPath)")
            print("Coordinator.viewController.flowCoordinator.nav: ", viewController.flowCoordinator?.nav ?? "nil", "VCs count: ",
                  viewController.flowCoordinator?.nav.viewControllers.count ?? "nil")
            viewController.flowCoordinator?.screen2()
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(flowCoordinator: flowCoordinator)
    }
}

struct ContentView: View {
    let deps = AppDependencies()
    var body: some View {
        View1(flowCoordinator: deps.flowCoordinator)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

let deps = AppDependencies()
//deps.flowCoordinator.start()
let nav = deps.flowCoordinator.nav
//let host = nav
let host = UIHostingController(rootView:   View1(flowCoordinator: deps.flowCoordinator) )
PlaygroundPage.current.liveView = host
</code>```

Body:
How is it possible that the navigation controller shown in the screenshot is described in the memory debugger as having 1 children (of type ContactsTableViewController) and at the same time in the lldb prompt is described as having 0 elements?

If you want more context or the code to reproduce it, please look at the code shown in: here

UPDATE:

I haven't run any other commands between the time I captured the memory graph and the time I ran the po command.

The minimal reproducible example is the following playground snippet ( I only have seen this strange behaviour when using a UIViewControllerRepresentable.Coordinator, that's why the minimal example is a bit complex):

import PlaygroundSupport
import SwiftUI
import UIKit

protocol Coordinator {
    var nav: UINavigationController { get }
    func start()
}

final class FlowCoordinator: Coordinator {
    struct Dependencies {
        let nav: UINavigationController
        let screen1Factory: () -> UIViewController
        let screen2Factory: () -> UIViewController
    }

    var nav: UINavigationController
    let screen1Factory: () -> UIViewController
    let screen2Factory: () -> UIViewController

    init(dependencies: FlowCoordinator.Dependencies) {
        self.nav = dependencies.nav
        self.screen1Factory = dependencies.screen1Factory
        self.screen2Factory = dependencies.screen2Factory
    }

    func start() {
        let vc = screen1Factory() as! ViewController
        vc.flowCoordinator = self
        nav.pushViewController(vc, animated: false)
        print("FlowCoordinator.started: flowCoordinator.nav: ", nav, "VCs count: ", nav.viewControllers.count)
    }

    func screen2() {
        print("Pushing screen2")
        let vc = screen2Factory() as! ViewController
        vc.flowCoordinator = self
        nav.pushViewController(vc, animated: false)
        print("Coordinator.viewController.flowCoordinator.nav: ", "VCs count: ",
              nav.viewControllers.count)
    }
}

final class ViewController: UITableViewController {
    weak var flowCoordinator: FlowCoordinator?

    // Array of cities to display in the table view
    let cities = ["New York", "Paris", "Tokyo"]

    init() {
        super.init(nibName: nil, bundle: nil)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CityCell")
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section
        return cities.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CityCell", for: indexPath)
        // Configure the cell...
        cell.textLabel?.text = cities[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        flowCoordinator?.screen2()
    }
}

final class AppDependencies {
    lazy var flowCoordinator: FlowCoordinator = {
        let navigationController = UINavigationController()
        navigationController.navigationBar.prefersLargeTitles = true
        let flowCoordinatorDependencies = FlowCoordinator.Dependencies(
            nav: navigationController,
            screen1Factory: makeViewController1,
            screen2Factory: makeViewController2)
        return FlowCoordinator(dependencies: flowCoordinatorDependencies)
    }()

    func makeViewController1() -> UIViewController {
        let vc = ViewController()
        vc.title = "View 1"
        return vc
    }

    func makeViewController2() -> UIViewController {
        let vc = ViewController()
        vc.title = "View 2"
        return vc
    }
}
[![enter image description here][1]][1]

struct View1: UIViewControllerRepresentable {
    let flowCoordinator: FlowCoordinator

    func makeUIViewController(context: Context) -> ViewController {
        return context.coordinator.viewController
    }

    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
    }
}

extension View1 {
    final class Coordinator: NSObject, UITableViewDelegate {
        var viewController: ViewController
        var flowCoordinator: FlowCoordinator
        init(flowCoordinator: FlowCoordinator) {
            self.flowCoordinator = flowCoordinator
            self.flowCoordinator.start()
            self.viewController = self.flowCoordinator.nav.viewControllers.first as! ViewController
            super.init()
            viewController.tableView.delegate = self
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("View1.tableView(_:didSelectRowAt:indexPath)")
            print("Coordinator.viewController.flowCoordinator.nav: ", viewController.flowCoordinator?.nav ?? "nil", "VCs count: ",
                  viewController.flowCoordinator?.nav.viewControllers.count ?? "nil")
            viewController.flowCoordinator?.screen2()
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(flowCoordinator: flowCoordinator)
    }
}

struct ContentView: View {
    let deps = AppDependencies()
    var body: some View {
        View1(flowCoordinator: deps.flowCoordinator)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

let deps = AppDependencies()
//deps.flowCoordinator.start()
let nav = deps.flowCoordinator.nav
//let host = nav
let host = UIHostingController(rootView:   View1(flowCoordinator: deps.flowCoordinator) )
PlaygroundPage.current.liveView = host


来源: stackexchange

问:
Pandas losing inheritance when subsetting dataframe
I made my own pandas class to add some custom methods, here's the code

```<code>Class Mypandas(pd.DataFrame):
    def foo(sefl):
        return self
</code>```

When I run the following, I get an AttributeError saying 'DataFrame' object has no attribute

```<code>df = Mypandas(df)
df = df.query('count > 0')
df.foo()
</code>```

I guess it's because I'm subsetting my df but as I instantiated Mypandas, should I still have access to df.foo()? Why is that? How can I counter this so I can still subset my df?

ContentLicense: CC BY-SA 4.0

Body:
I made my own pandas class to add some custom methods, here's the code

Class Mypandas(pd.DataFrame):
    def foo(sefl):
        return self

When I run the following, I get an AttributeError saying 'DataFrame' object has no attribute

df = Mypandas(df)
df = df.query('count > 0')
df.foo()

I guess it's because I'm subsetting my df but as I instantiated Mypandas, should I still have access to df.foo()? Why is that? How can I counter this so I can still subset my df?


问:
How do I get a sprite to stay within the bounds of a tilemap?
I have programmatically generated sprites based on three pre-existing sprites. They basically multiply in the Start() method. I have created a 2d tilemap that should surround the generated sprites. However, the sprites fall through the tilemap due to gravity.

This is my Start() method with additional methods though I don't suspect it (the Start() method) to be the source of the issue:

public GameObject area;
public List<GameObject> objects;

public int ship_count = 0;
public int ship_limit = 200;
public int ships_per_frame = 1;

public float spawn_circle_radius = 7;
public float death_circle_radius = .2f;

public float fastest = 7;
public float slowest = 2;

void Start()
{
   for (int i = 0, j = 0; i < ship_limit; ++i, this.ship_count++)
   {
       if (j < objects.Count)
           AddObject(GetRandomPosition(), objects[j++]);
       else j = 0;
   }
}

Vector3 GetRandomPosition()
{
   Vector3 position = Random.insideUnitCircle.normalized;
   position *= spawn_circle_radius;
   position += area.transform.position;
   return position;
}

Objects AddObject(Vector3 position, GameObject obj)
{
   GameObject newShip = Instantiate(obj, position, Quaternion.FromToRotation(Vector3.up, area.transform.position - position), gameObject.transform);
   Objects script = newShip.GetComponent<Objects>();
   script.Spawner = this;
   script.Area = area;
   script.speed = Random.Range(slowest, fastest);
   return script;
}
```

I set the tilemap to have Box Collider, Tilemap Collider, Composite Collider and a 2D static RigidBody. The sprites have a dynamic 2D RigidBody and Box Collider.

How do I get the sprite to stay within the bounds rather than fall through the bounds of the tilemap?

Body:
I have programmatically generated sprites based on three pre-existing sprites. They basically multiply in the Start() method. I have created a 2d tilemap that should surround the generated sprites. However, the sprites fall through the tilemap due to gravity.

This is my Start() method with additional methods though I don't suspect it (the Start() method) to be the source of the issue:

public GameObject area;
public List<GameObject> objects;

public int ship_count = 0;
public int ship_limit = 200;
public int ships_per_frame = 1;

public float spawn_circle_radius = 7;
public float death_circle_radius = .2f;

public float fastest = 7;
public float slowest = 2;

void Start()
{
   for (int i = 0, j = 0; i < ship_limit; ++i, this.ship_count++)
   {
       if (j < objects.Count)
           AddObject(GetRandomPosition(), objects[j++]);
       else j = 0;
   }
}

Vector3 GetRandomPosition()
{
   Vector3 position = Random.insideUnitCircle.normalized;
   position *= spawn_circle_radius;
   position += area.transform.position;
   return position;
}

Objects AddObject(Vector3 position, GameObject obj)
{
   GameObject newShip = Instantiate(obj, position, Quaternion.FromToRotation(Vector3.up, area.transform.position - position), gameObject.transform);
   Objects script = newShip.GetComponent<Objects>();
   script.Spawner = this;
   script.Area = area;
   script.speed = Random.Range(slowest, fastest);
   return script;
}

I set the tilemap to have Box Collider, Tilemap Collider, Composite Collider and a 2D static RigidBody. The sprites have a dynamic 2D RigidBody and Box Collider.

How do I get the sprite to stay within the bounds rather than fall through the bounds of the tilemap?


问:
Flutter - Text align justify with no half filled lines
I'm building a Quran app where I want all pages to have fully filled lines

I tried to use TextAlign.justify and it kinda helped and got this output from it:

The problem is that the last line is not filled all the way out like this for example:

I tried to use TextPainter but it removed the onTapGestureRecognizer.
How can I get such an output without removing the tap capability? I also tried line and letter spacing but didn't work too.


问:
Xamarin.Android.Support issue
Warning NU1608  Detected package version outside of dependency constraint: Xamarin.Android.Support.Fragment 27.0.2.1 requires Xamarin.Android.Support.Compat (= 27.0.2.1) but version Xamarin.Android.Support.Compat 28.0.0.3 was resolved.

All I did was to install Xamarin.Android.Support.Compat. I didn't specify any particular version. I don't see anything with the name Support.Fragment.

Not sure what to do.

Title: Xamarin.Android.Support issue


问:
Anyway to join this query and make one query in django filter
```<code>    post_search_comments= PostInLanguages.objects.filter(comment_data__is_post_comment=True).annotate(c=Count('comment_data', distinct=True)).filter(c__gte=0)
        post_search_likes =  PostInLanguages.objects.annotate(l=Count('like_model', distinct=True)).filter(l__gte = 1)

</code>```

I need to make one query from these above queries.  Needed post objects which has minimum likes and minimum comments.

For now im using intersection

```<code>        intersection = post_search_comments & post_search_likes
        print(intersection)

        paginator = CustomPageNumberPagination()
        page = paginator.paginate_queryset(post_search_comments, request)
        serializer = PostInLanguagesSerializer(page, many=True)
        response = paginator.get_paginated_response(serializer.data)
        return response
</code>```

Body:
    post_search_comments= PostInLanguages.objects.filter(comment_data__is_post_comment=True).annotate(c=Count('comment_data', distinct=True)).filter(c__gte=0)
        post_search_likes =  PostInLanguages.objects.annotate(l=Count('like_model', distinct=True)).filter(l__gte = 1)

I need to make one query from these above queries.  Needed post objects which has minimum likes and minimum comments.

For now im using intersection

        intersection = post_search_comments & post_search_likes
        print(intersection)

        paginator = CustomPageNumberPagination()
        page = paginator.paginate_queryset(post_search_comments, request)
        serializer = PostInLanguagesSerializer(page, many=True)
        response = paginator.get_paginated_response(serializer.data)
        return response


问:
Widget Extension SwiftUI Preview won't load on UiKit Project
I'm trying to add a WidgetKit Extension to my Swift UiKit project. I've activated the target and I haven't changed any of the code yet and the preview won't load. I've tried restarting xcode and my mac and that hasn't worked.


问:
Data read by fread is longer than what I wrote with fwrite
I made a program that can look for prime numbers. It works fine until it hits a point where the file is suddenly longer than what I wrote with fwrite. Here is the code. I am sorry, it is a bit long, but it is complete and executable.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

long long *loadPrimeNums(char *fileName);
void putPrimeNumsInList(long long *primeNums);
void addIntNode(void);
void initialize(void);
void DestroyIntNodes(void);
void writeInFile(void);
void run(void);

int main ()
{
    initialize();
    putPrimeNumsInList(loadPrimeNums("primeNums"));
    run();

    writeInFile();
    DestroyIntNodes();
    _fcloseall();
    return 0;
}
</code>```

Second file:

```<code>#include <stdio.h>
#include <stdlib.h>

struct longLongNode
{
    long long value;
    struct longLongNode *next;
};

long long *loadPrimeNums(char *fileName);
void putPrimeNumsInList(long long *primeNums);
void addLongLongNode(void);
void initialize(void);
void DestroyIntNodes(void);
void writeInFile(void);
void run(void);

FILE *primeNums_fp;
long long currentOffset;
struct longLongNode *head, *tail, *lastOldPrimeNum;

void run()
{
    struct longLongNode *current;
    current = head;

    int isPrime = 1;
    for (int i = 0; i < 100; i++)
    {
        while (current != NULL)
        {
            if (currentOffset % current->value == 0)
            {
                isPrime = 0;
                break;
            }
            current = current->next;
        }
        if (isPrime == 0)
        {
            isPrime = 1;
        }
        else
        {
            addLongLongNode();
        }
        currentOffset++;
        current = head;
    }
}

void writeInFile()
{
    int numberOfNewPrimes = 0;
    long long *newPrimes;
    struct longLongNode *current;
    current = lastOldPrimeNum;

    while (current->next != NULL)
    {
        numberOfNewPrimes++;
        current = current->next;
    }

    if (numberOfNewPrimes > 0)
    {
        current = lastOldPrimeNum->next;
        newPrimes = (long long *)malloc(sizeof *newPrimes * numberOfNewPrimes);

        for (int i = 0; i < numberOfNewPrimes; i++)
        {
            newPrimes[i] = current->value;
            current = current->next;
        }
        fseek(primeNums_fp, 0L, 2);
        fwrite(newPrimes, sizeof *newPrimes, numberOfNewPrimes, primeNums_fp);
        printf("Freeing newPrimes: The array that is used to write the new prime numbers to file.\n");
        free(newPrimes);
    }
}

void initialize()
{
    head = (struct longLongNode *)malloc(sizeof *head);
    head->value = 2;
    head->next = NULL;
    lastOldPrimeNum = head;
}

void addLongLongNode()
{
    struct longLongNode *temp;
    temp = (struct longLongNode *)malloc(sizeof *temp);
    temp->value = currentOffset;
    temp->next = NULL;
    tail->next = temp;
    tail = temp;
}

long long *loadPrimeNums(char *fileName)
{
    int num;
    long long *ret;
    primeNums_fp = fopen("primeNums", "a+");
    fseek(primeNums_fp, 0L, 2);
    if (ftell(primeNums_fp) != 0)
    {
        if (ftell(primeNums_fp) % sizeof *ret == 0)
        {
            num = ftell(primeNums_fp) / sizeof *ret;
            ret = (long long *)malloc(sizeof *ret * (num + 1));
            rewind(primeNums_fp);
            fread(ret, sizeof *ret, num, primeNums_fp);
            ret[num] = -1;
            return ret;
        }
        else if (ftell(primeNums_fp) != -1)
        {
            printf("ERROR!!! ftell(fp): %d", ftell(primeNums_fp));
            _fcloseall();
            exit(0);
        }
    }
    return NULL;
}

void putPrimeNumsInList(long long *primeNums)
{
    struct longLongNode *current, *temp;

    current = head;
    tail = head;

    if (primeNums != NULL)
    {
        for (int i = 0; primeNums[i] != -1; i++)
        {
            temp = (struct longLongNode *)malloc(sizeof *temp);
            temp->value = primeNums[i];
            temp->next = NULL;
            current->next = temp;
            current = temp;
        }
        tail = current;
        lastOldPrimeNum = current;
    }
    currentOffset = current->value + 1;
    printf("Freeing primeNums: The array that contains the initially loaded prime numbers of the file.\n");
    free(primeNums);
}

void DestroyIntNodes()
{
    struct longLongNode *current, *next;
    current = head;
    for (int i = 1; current != NULL; i++)
    {
        next = current->next;
        printf("%d: Freeing %d\n", i, current->value);
        free(current);
        current = next;
    }
}
</code>```

What I get after finding 384 prime numbers is an error message that I made myself which shows how big the file is. The file should be divisible by 8, because the prime numbers are stored as long long integers, but at some point I got a file size of 3073.

Edit: You need to run the program multiple times for the error to occur. I did not know how to multithread, so I made it so it stops after a 100 iterations. Then the prime numbers it found will be stored in a file which should be divisible by 8, but isn't.

Edit2: At the start, the file does not exist. And I am using Windows 10. I am trying now the suggestion of setting fopen mode "ab+".

Edit3: Solved thanks to @user3121023!!

Body:
I made a program that can look for prime numbers. It works fine until it hits a point where the file is suddenly longer than what I wrote with fwrite. Here is the code. I am sorry, it is a bit long, but it is complete and executable.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

long long *loadPrimeNums(char *fileName);
void putPrimeNumsInList(long long *primeNums);
void addIntNode(void);
void initialize(void);
void DestroyIntNodes(void);
void writeInFile(void);
void run(void);

int main ()
{
    initialize();
    putPrimeNumsInList(loadPrimeNums("primeNums"));
    run();

    writeInFile();
    DestroyIntNodes();
    _fcloseall();
    return 0;
}

Second file:

#include <stdio.h>
#include <stdlib.h>

struct longLongNode
{
    long long value;
    struct longLongNode *next;
};

long long *loadPrimeNums(char *fileName);
void putPrimeNumsInList(long long *primeNums);
void addLongLongNode(void);
void initialize(void);
void DestroyIntNodes(void);
void writeInFile(void);
void run(void);

FILE *primeNums_fp;
long long currentOffset;
struct longLongNode *head, *tail, *lastOldPrimeNum;

void run()
{
    struct longLongNode *current;
    current = head;

    int isPrime = 1;
    for (int i = 0; i < 100; i++)
    {
        while (current != NULL)
        {
            if (currentOffset % current->value == 0)
            {
                isPrime = 0;
                break;
            }
            current = current->next;
        }
        if (isPrime == 0)
        {
            isPrime = 1;
        }
        else
        {
            addLongLongNode();
        }
        currentOffset++;
        current = head;
    }
}

void writeInFile()
{
    int numberOfNewPrimes = 0;
    long long *newPrimes;
    struct longLongNode *current;
    current = lastOldPrimeNum;

    while (current->next != NULL)
    {
        numberOfNewPrimes++;
        current = current->next;
    }

    if (numberOfNewPrimes > 0)
    {
        current = lastOldPrimeNum->next;
        newPrimes = (long long *)malloc(sizeof *newPrimes * numberOfNewPrimes);

        for (int i = 0; i < numberOfNewPrimes; i++)
        {
            newPrimes[i] = current->value;
            current = current->next;
        }
        fseek(primeNums_fp, 0L, 2);
        fwrite(newPrimes, sizeof *newPrimes, numberOfNewPrimes, primeNums_fp);
        printf("Freeing newPrimes: The array that is used to write the new prime numbers to file.\n");
        free(newPrimes);
    }
}

void initialize()
{
    head = (struct longLongNode *)malloc(sizeof *head);
    head->value = 2;
    head->next = NULL;
    lastOldPrimeNum = head;
}

void addLongLongNode()
{
    struct longLongNode *temp;
    temp = (struct longLongNode *)malloc(sizeof *temp);
    temp->value = currentOffset;
    temp->next = NULL;
    tail->next = temp;
    tail = temp;
}

long long *loadPrimeNums(char *fileName)
{
    int num;
    long long *ret;
    primeNums_fp = fopen("primeNums", "a+");
    fseek(primeNums_fp, 0L, 2);
    if (ftell(primeNums_fp) != 0)
    {
        if (ftell(primeNums_fp) % sizeof *ret == 0)
        {
            num = ftell(primeNums_fp) / sizeof *ret;
            ret = (long long *)malloc(sizeof *ret * (num + 1));
            rewind(primeNums_fp);
            fread(ret, sizeof *ret, num, primeNums_fp);
            ret[num] = -1;
            return ret;
        }
        else if (ftell(primeNums_fp) != -1)
        {
            printf("ERROR!!! ftell(fp): %d", ftell(primeNums_fp));
            _fcloseall();
            exit(0);
        }
    }
    return NULL;
}

void putPrimeNumsInList(long long *primeNums)
{
    struct longLongNode *current, *temp;

    current = head;
    tail = head;

    if (primeNums != NULL)
    {
        for (int i = 0; primeNums[i] != -1; i++)
        {
            temp = (struct longLongNode *)malloc(sizeof *temp);
            temp->value = primeNums[i];
            temp->next = NULL;
            current->next = temp;
            current = temp;
        }
        tail = current;
        lastOldPrimeNum = current;
    }
    currentOffset = current->value + 1;
    printf("Freeing primeNums: The array that contains the initially loaded prime numbers of the file.\n");
    free(primeNums);
}

void DestroyIntNodes()
{
    struct longLongNode *current, *next;
    current = head;
    for (int i = 1; current != NULL; i++)
    {
        next = current->next;
        printf("%d: Freeing %d\n", i, current->value);
        free(current);
        current = next;
    }
}

What I get after finding 384 prime numbers is an error message that I made myself which shows how big the file is. The file should be divisible by 8, because the prime numbers are stored as long long integers, but at some point I got a file size of 3073.

Edit: You need to run the program multiple times for the error to occur. I did not know how to multithread, so I made it so it stops after a 100 iterations. Then the prime numbers it found will be stored in a file which should be divisible by 8, but isn't.

Edit2: At the start, the file does not exist. And I am using Windows 10. I am trying now the suggestion of setting fopen mode "ab+".

Edit3: Solved thanks to @user3121023!!


问:
ODR and C++ Versioning for Shared Library Wrapper
For simplicity, I will omit things like proper typedefs to opaque structs instead of void *, Windows calling conventions, fixed integer types, etc.

Suppose I have the following files:

CApi.h -- Shared library header with C linkage for portability and hiding proprietary code.

#define LIB_API  // library import/export details

extern "C" {

typedef int error;

error LIB_API lib_foo_create(void ** foo);
error LIB_API lib_foo_destroy(void * foo);
error LIB_API lib_foo_func(void * foo, int * out);

error LIB_API lib_bar_create(void ** bar);
error LIB_API lib_bar_destroy(void * bar);
error LIB_API lib_bar_func(void * bar, int * out); // Suppose this internally uses Foo::func from CxxApi.hpp with C++17

} // extern C
```
<p>CxxApi.hpp -- Header only wrapper to simplify API usage.</p>
<pre class="lang-cpp prettyprint-override"><code>#include "CApi.h"

namespace lib {

namespace detail {

template < typename Return = void, typename Func, typename... Args >
Return c_api(Func func)
{
    // Not sure how this affects ODR if client and provider code use different versions,
    // but neither see each other's code usage.

    #if __cplusplus >= 201703L // C++17
    // more efficient implmentation (e.g. fold expressions)
    #else
    // fallback implmentation (e.g. recursion)
    #endif
}

} // namespace lib::detail

class Foo
{
public:
    Foo() { detail::c_api(lib_foo_create, &handle_); }

    ~Foo() { detail::c_api(lib_foo_destroy, handle_); }

    int func() { return detail::c_api<int>(lib_foo_func, handle_); }

private:
    void * handle_;
};

struct Bar
{
public:
    Bar() { detail::c_api(lib_bar_create, &handle_); }

    ~Bar() { detail::c_api(lib_bar_destroy, handle_); }

    int func() { return detail::c_api<int>(lib_bar_func, handle_); }

private:
    void * handle_;
};

} // namespace lib
</code>```

If I, the API provider, compile this using C++17, but the client using the API uses C++11, is ODR violated with lib::detail::c_api?
I believe it is not because lib_bar_func's definition is in a different translation unit than client code, but I am not positive.

Body:
For simplicity, I will omit things like proper typedefs to opaque structs instead of void *, Windows calling conventions, fixed integer types, etc.

Suppose I have the following files:

CApi.h -- Shared library header with C linkage for portability and hiding proprietary code.

#define LIB_API  // library import/export details

extern "C" {

typedef int error;

error LIB_API lib_foo_create(void ** foo);
error LIB_API lib_foo_destroy(void * foo);
error LIB_API lib_foo_func(void * foo, int * out);

error LIB_API lib_bar_create(void ** bar);
error LIB_API lib_bar_destroy(void * bar);
error LIB_API lib_bar_func(void * bar, int * out); // Suppose this internally uses Foo::func from CxxApi.hpp with C++17

} // extern C

CxxApi.hpp -- Header only wrapper to simplify API usage.

#include "CApi.h"

namespace lib {

namespace detail {

template < typename Return = void, typename Func, typename... Args >
Return c_api(Func func)
{
    // Not sure how this affects ODR if client and provider code use different versions,
    // but neither see each other's code usage.

    #if __cplusplus >= 201703L // C++17
    // more efficient implmentation (e.g. fold expressions)
    #else
    // fallback implmentation (e.g. recursion)
    #endif
}

} // namespace lib::detail

class Foo
{
public:
    Foo() { detail::c_api(lib_foo_create, &handle_); }

    ~Foo() { detail::c_api(lib_foo_destroy, handle_); }

    int func() { return detail::c_api<int>(lib_foo_func, handle_); }

private:
    void * handle_;
};

struct Bar
{
public:
    Bar() { detail::c_api(lib_bar_create, &handle_); }

    ~Bar() { detail::c_api(lib_bar_destroy, handle_); }

    int func() { return detail::c_api<int>(lib_bar_func, handle_); }

private:
    void * handle_;
};

} // namespace lib

If I, the API provider, compile this using C++17, but the client using the API uses C++11, is ODR violated with lib::detail::c_api?
I believe it is not because lib_bar_func's definition is in a different translation unit than client code, but I am not positive.


问:
Recompile only changed files in Go when using C++ lib
I am new to go. I use go-tdlib which in turn uses tdlib written in C++. First time the compilation took about 15-20 minutes, then I literally added one commented line to my Go main func (I just copypasted the example from go-tdlib, so it is just one small main func) and when I want to run the program it again takes 15-20 minutes to compile it. Is there any way to recompile only changed file? I tried go build and go install and I did not find yet any helpful solutions to this.

As I understand, Go compiles everything to one executable, and any change to one file triggers recompilation of everything. Is this correct? Is there any way to stop this? It is really annoying to wait 15-20 minutes when you added only one line to your main func.

Btw, I think it's due to the C++ lib, because if I remove all usages of the lib from the code, then it compiles as fast as expected.


问:
Can I use pycript to get the contents of a webiste and access it in javascript without same origin?
I dont really know python that well, but I was able to scrounge up a script that hits a website and downloads the data from it, saving that data to a file. I used python over javascript because fetch is limited by cors same origin and python is not. I also didnt want to set up a proxy server. I added a file input field on my site for people to upload what the python script saves. Then I remembered pyscript was a thing. I tried running my python script in pyscript but got errors about the imports... I have no clue what I am doing here. If anyone has some advice.

Here is the python script:

import sys
import json
import requests
from bs4 import BeautifulSoup

# Declare variables
review_limit = 15
comment_limit = 4

# Get the list of id numbers from the command line arguments
ids = sys.argv[1:]

# If no id numbers are provided, ask the user to enter them
if not ids:
    ids = input("Enter the id numbers separated by a space: ").split()

# Initialize the data object
data = {}

for id in ids:
    # Make sure it's a valid number
    if id and int(id) > 0:
        url_model = f"https://example.com/{id}/{review_limit}/{comment_limit}/"

        # Send a GET request to the page and parse the response
        response = requests.get(url_model)
        doc = BeautifulSoup(response.text, "html.parser")

        # Extract the data from the response
        page_data = doc.find(id="jsonDiv").text

        # Parse the data text as JSON
        page_data = json.loads(page_data)

        # Add the data to the data object
        data[id] = {
            "pageData": page_data
        }

# Write the data object to a file, pretty-printing the JSON data
with open("data.json", "w") as outfile:
    json.dump(data, outfile, indent=2)
```

The idea would be that the user is asked for ids and for each id it gets the data from the website. That data is then added to a JSON object that has the data of all the ids and then sent back to Javascript to be processed further.

Body:
I dont really know python that well, but I was able to scrounge up a script that hits a website and downloads the data from it, saving that data to a file. I used python over javascript because fetch is limited by cors same origin and python is not. I also didnt want to set up a proxy server. I added a file input field on my site for people to upload what the python script saves. Then I remembered pyscript was a thing. I tried running my python script in pyscript but got errors about the imports... I have no clue what I am doing here. If anyone has some advice.

Here is the python script:

import sys
import json
import requests
from bs4 import BeautifulSoup

# Declare variables
review_limit = 15
comment_limit = 4

# Get the list of id numbers from the command line arguments
ids = sys.argv[1:]

# If no id numbers are provided, ask the user to enter them
if not ids:
    ids = input("Enter the id numbers separated by a space: ").split()

# Initialize the data object
data = {}

for id in ids:
    # Make sure it's a valid number
    if id and int(id) > 0:
        url_model = f"https://example.com/{id}/{review_limit}/{comment_limit}/"

        # Send a GET request to the page and parse the response
        response = requests.get(url_model)
        doc = BeautifulSoup(response.text, "html.parser")

        # Extract the data from the response
        page_data = doc.find(id="jsonDiv").text

        # Parse the data text as JSON
        page_data = json.loads(page_data)

        # Add the data to the data object
        data[id] = {
            "pageData": page_data
        }

# Write the data object to a file, pretty-printing the JSON data
with open("data.json", "w") as outfile:
    json.dump(data, outfile, indent=2)

The idea would be that the user is asked for ids and for each id it gets the data from the website. That data is then added to a JSON object that has the data of all the ids and then sent back to Javascript to be processed further.


问:
on_message sending infinte messages on compose
im trying to operate 2 bots within pyrogram(MAIN_BOT and GROUP_BOT) and whenever im sending a message to MAIN_BOT its suppost to send 1 time 'press /start', instead it sends the message endlessly like a loop..
i have 2 on_message and another function that needs to update things every 60 seconds.

```<code>import asyncio
import Keys
from pyrogram import Client, filters, compose

app = Client(
    "app",
    api_id=Keys.api_id,
    api_hash=Keys.api_hash,
    bot_token=Keys.MAIN_BOT
)

create_app = Client(
    "my_account",
    api_id=Keys.api_id,
    api_hash=Keys.api_hash,
    bot_token=Keys.GROUP_BOT
)

@create_app.on_message(filters.text)
async def exchangeAndSend(client, msg):
    await create_app.delete_messages(msg.chat.id, msg.id)
    await msg.reply(text=msg.from_user.first_name + ": " + text)

@app.on_message(filters.text)
async def MainWordsExchange(client, msg):
    await msg.reply(text="press /start")

async def close_groups():
    while True:
        await asyncio.sleep(60)
        for i in groupList:
            i.toString()
            if int(time.time()) - i.time_created > Keys.EXPIRED_TIME_MIN * 60:
                groupList.remove(i)
        print('<---end of loop--->')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(close_groups())
    loop.create_task(compose([app, create_app]))
    loop.run_forever()

</code>```

eventually the create_app.on_message(GROUP_BOT) works ok and send exactly 1 message but the app.on_message(MAIN_BOT) sending multiple 'press /start' until i stop the program.

how can i fix that?

Body:
im trying to operate 2 bots within pyrogram(MAIN_BOT and GROUP_BOT) and whenever im sending a message to MAIN_BOT its suppost to send 1 time 'press /start', instead it sends the message endlessly like a loop..
i have 2 on_message and another function that needs to update things every 60 seconds.

import asyncio
import Keys
from pyrogram import Client, filters, compose

app = Client(
    "app",
    api_id=Keys.api_id,
    api_hash=Keys.api_hash,
    bot_token=Keys.MAIN_BOT
)

create_app = Client(
    "my_account",
    api_id=Keys.api_id,
    api_hash=Keys.api_hash,
    bot_token=Keys.GROUP_BOT
)

@create_app.on_message(filters.text)
async def exchangeAndSend(client, msg):
    await create_app.delete_messages(msg.chat.id, msg.id)
    await msg.reply(text=msg.from_user.first_name + ": " + text)

@app.on_message(filters.text)
async def MainWordsExchange(client, msg):
    await msg.reply(text="press /start")

async def close_groups():
    while True:
        await asyncio.sleep(60)
        for i in groupList:
            i.toString()
            if int(time.time()) - i.time_created > Keys.EXPIRED_TIME_MIN * 60:
                groupList.remove(i)
        print('<---end of loop--->')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(close_groups())
    loop.create_task(compose([app, create_app]))
    loop.run_forever()

eventually the create_app.on_message(GROUP_BOT) works ok and send exactly 1 message but the app.on_message(MAIN_BOT) sending multiple 'press /start' until i stop the program.

how can i fix that?


问:
Otp verification using firebase in node js? and set the timeout init
How to set the otp verification in firebase using node js or express.js  and set otp should expries after sometime and new otp can be generated after specific time ?

I tried to use the firebase admin sdk but cannot understand how to implement the otp verification init.


问:
Rails JS assets not present in production (Heroku)
Building a Rails 7 app, which works fine in development. When uploading to Heroku, JS doesn't work and no JS is in the asset folder and I get the following errors. CSS works fine:

```<code>2022-12-31T09:21:44.860222+00:00 heroku[router]: at=info method=GET path="/assets/bootstrap" host=xxx.herokuapp.com request_id=27e5c00d-8913-46da-a510-7d975f12a31f fwd="194.191.238.4" dyno=web.1 connect=0ms service=6ms status=404 bytes=1902 protocol=https
2022-12-31T09:21:44.857991+00:00 heroku[router]: at=info method=GET path="/assets/controllers" host=xxx.herokuapp.com request_id=d227fc0d-4cd3-4e24-8586-9e8912316bb9 fwd="194.191.238.4" dyno=web.1 connect=0ms service=3ms status=404 bytes=1902 protocol=https
</code>```

I am using Rails 7.0.4 with standard settings (incl. Import Maps). Any suggestions? Thanks!

The only "solution" so far is to set the following to "true", which is not a valid fix.

```<code>config.assets.compile = false
</code>```

Setting the following to "true" did not bring any results.

```<code>config.public_file_server.enabled = true
</code>```

Body:
Building a Rails 7 app, which works fine in development. When uploading to Heroku, JS doesn't work and no JS is in the asset folder and I get the following errors. CSS works fine:

2022-12-31T09:21:44.860222+00:00 heroku[router]: at=info method=GET path="/assets/bootstrap" host=xxx.herokuapp.com request_id=27e5c00d-8913-46da-a510-7d975f12a31f fwd="194.191.238.4" dyno=web.1 connect=0ms service=6ms status=404 bytes=1902 protocol=https
2022-12-31T09:21:44.857991+00:00 heroku[router]: at=info method=GET path="/assets/controllers" host=xxx.herokuapp.com request_id=d227fc0d-4cd3-4e24-8586-9e8912316bb9 fwd="194.191.238.4" dyno=web.1 connect=0ms service=3ms status=404 bytes=1902 protocol=https

I am using Rails 7.0.4 with standard settings (incl. Import Maps). Any suggestions? Thanks!

The only "solution" so far is to set the following to "true", which is not a valid fix.

config.assets.compile = false

Setting the following to "true" did not bring any results.

config.public_file_server.enabled = true


问:
Cannot import FirebaseMessagingService even with right dependecies
I'm trying to connect firebase to my app for the cloud messaging services. I made all the changes needed in gradle files that docs mentioned.
here are my grade files:

Project Level:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.1.0-beta01'
    }
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven {url "https://maven.google.com"}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
        classpath 'com.google.gms:google-services:4.3.14'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven {url "https://maven.google.com"}
    }
}
</code>```

Module Level:

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.codax.codax_app"
        minSdk 23
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_9
        targetCompatibility JavaVersion.VERSION_1_9
    }
    buildToolsVersion '32.1.0-rc1'
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'junit:junit:4.13.2'
    implementation 'androidx.test.ext:junit:1.1.3'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.firebase:firebase-messaging:23.1.1'

}
</code>```

When I sync gradle files I get no error but when trying to import firebase like this:

```<code>import com.google.firebase.messaging.FirebaseMessagingService;
</code>```

i get this error : Cannot resolve firebase

I tried cleaning and invalidating the cache(i use android studio) and resyncing gradle files but nothing helped.
and there is no other path that contains the firebase classes.

What am i doing wrong here? thanks in advance.

Body:
I'm trying to connect firebase to my app for the cloud messaging services. I made all the changes needed in gradle files that docs mentioned.
here are my grade files:

Project Level:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.1.0-beta01'
    }
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven {url "https://maven.google.com"}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
        classpath 'com.google.gms:google-services:4.3.14'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
        maven { url "https://jitpack.io" }
        maven {url "https://maven.google.com"}
    }
}

Module Level:

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.codax.codax_app"
        minSdk 23
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_9
        targetCompatibility JavaVersion.VERSION_1_9
    }
    buildToolsVersion '32.1.0-rc1'
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'junit:junit:4.13.2'
    implementation 'androidx.test.ext:junit:1.1.3'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.firebase:firebase-messaging:23.1.1'

}

When I sync gradle files I get no error but when trying to import firebase like this:

import com.google.firebase.messaging.FirebaseMessagingService;

i get this error : Cannot resolve firebase

I tried cleaning and invalidating the cache(i use android studio) and resyncing gradle files but nothing helped.
and there is no other path that contains the firebase classes.

What am i doing wrong here? thanks in advance.


问:
DRY: how to get a basic React/Apollo web app and python GraphQL backend API going with minimal duplication?
I'm an experienced SWE but sort of new to modern web development. I'd like to build a demo/prototype website for a startup idea with minimal time. I'd like to have the frontend tied to a backend DB store up front so it's fully functional. I'd like advice on the best stack to use. I'd like a python backend, and I'm planning on React for the frontend, with GraphQL (unless this is a dumb idea for a prototype... I'd like to learn about it though.)

I feel like there is a ton of redundancy in terms of data object models. I can make a GraphQL schema (I was thinking of using ariadne + FastAPI) but then I still need to build DB tables, or create an object model e.g. in Django. And then of course there is all the React code to make forms to edit stuff. My app will require a significant amount of data entry on the website to set up users and lots of metadata. I built a ton of forms etc in React, backed by Apollo client.

Any suggestions -- am I on the right track or is there a quicker way to a prototype?

Are there any tools that autogenerate some of this code? E.g., I expected I could start with a GraphQL schema and there would be a way to auto-extract a reasonable object model like that used in Django. Or conversely, maybe I could build DB tables and auto-gen a basic GraphQL service. If these don't exist it seems like an opportunity, since I'm seeing so much redundancy... and in prototype phase I don't care about keeping the DB and the API totally independent; I'm okay to trash the DB over and over and re-generate until I get to a beta state, etc.


问:
Firebase Authentication using React - issue with page refresh
I am trying to create a basic React app with Firebase and Zustand. There is a login page and a dashboard page. You can only view the dashboard page if you are logged in otherwise you get redirected to login page. After logging in, the user is redirected to dashboard page which displays user email id. The problem is when I refresh the dashboard page after logging in, in spite of being logged in, I get redirected to login page because in the first render,username is null.Code is attached. How can I get around this behavior?</p>
```<code>function App() {
  const userData = useUserStore((state) => state.setUser);
  useEffect(() => {
    const authState = onAuthStateChanged(auth, (user) => {
      if (user) {
        userData(user.email);
      } else {
        console.log("no user");
      }
    });

    return () => {
      authState();
    };
  }, []);

  return <RouterProvider router={router} />;
}
</code>```
```<code>function Dashboard() {
  const username = useUserStore((state) => state.username);

  return username ? (
    <div>Hi, {username}</div>
  ) : (
    <Navigate to="/login" />
  );
}
</code>```

Body:
I am trying to create a basic React app with Firebase and Zustand. There is a login page and a dashboard page. You can only view the dashboard page if you are logged in otherwise you get redirected to login page. After logging in, the user is redirected to dashboard page which displays user email id. The problem is when I refresh the dashboard page after logging in, in spite of being logged in, I get redirected to login page because in the first render,username is null.Code is attached. How can I get around this behavior?

function App() {
  const userData = useUserStore((state) => state.setUser);
  useEffect(() => {
    const authState = onAuthStateChanged(auth, (user) => {
      if (user) {
        userData(user.email);
      } else {
        console.log("no user");
      }
    });

    return () => {
      authState();
    };
  }, []);

  return <RouterProvider router={router} />;
}

function Dashboard() {
  const username = useUserStore((state) => state.username);

  return username ? (

Hi, {username}

  ) : (
    <Navigate to="/login" />
  );
}


问:
The following question is of the topic:- OOPS with Java, Polymorphism in particular
Let's assume we have a case of Multi-level inheritance over here, where there is an 'Animal' super class, and a 'Dog' as a subclass. Now i'll mention the code here which is supposed to involve method overriding. Both the Animal class and the class 'Dog' have the common method called 'eat()'. So my question is if i want to access the eat() function of the class 'Dog', then the syntax should be as follows:-

```<code>public class Test
{
public static void main(String args[])
{
Dog obj = new Dog();
obj.eat();
}
}
</code>```

But instead of this, the book mentions to use the super class during creation of the object.
and the actual code looks somewhat like this:-

```<code>public class Test
{
public static void main(String args[])
{
Animal obj = new Dog();
obj.eat();
}
}
</code>```

So, what's the point in using the superclass for creation of the object, when using the subclass for creation of the object works perfectly fine?

I tried to figure out the reason, but couldn't fine anything specific enought to satite my queries. Thanks in advance!

Body:
Let's assume we have a case of Multi-level inheritance over here, where there is an 'Animal' super class, and a 'Dog' as a subclass. Now i'll mention the code here which is supposed to involve method overriding. Both the Animal class and the class 'Dog' have the common method called 'eat()'. So my question is if i want to access the eat() function of the class 'Dog', then the syntax should be as follows:-

public class Test
{
public static void main(String args[])
{
Dog obj = new Dog();
obj.eat();
}
}

But instead of this, the book mentions to use the super class during creation of the object.
and the actual code looks somewhat like this:-

public class Test
{
public static void main(String args[])
{
Animal obj = new Dog();
obj.eat();
}
}

So, what's the point in using the superclass for creation of the object, when using the subclass for creation of the object works perfectly fine?

I tried to figure out the reason, but couldn't fine anything specific enought to satite my queries. Thanks in advance!


问:
Deserializing claims fails for Auth0 Token
I'm using auth0 and am passing the generated token to the backend for some processing.
I need to validate the token and fetch some data from it (mainly email).

Checking the JWT on jwt.io and it appears valid with all relevant information there.

I'm using the provided auth0 middleware https://github.com/auth0/go-jwt-middleware to parse the token on my end. Everything runs fine until it gets to deserializeClaims.

I'm then hit with: could not get token claims: square/go-jose: unsupported key type/format)

Even just some insight on how to better troubleshoot this would be helpful, as it stands, I have no idea what is wrong.

```<code>// ValidateToken validates the passed in JWT using the jose v2 package.
func (v *Validator) ValidateToken(ctx context.Context, tokenString string) (interface{}, error) {
    token, err := jwt.ParseSigned(tokenString)
    if err != nil {
        return nil, fmt.Errorf("could not parse the token: %w", err)
    }

    if err = validateSigningMethod(string(v.signatureAlgorithm), token.Headers[0].Algorithm); err != nil {
        return nil, fmt.Errorf("signing method is invalid: %w", err)
    }

    registeredClaims, customClaims, err := v.deserializeClaims(ctx, token)  <- this fails
    if err != nil {
        return nil, fmt.Errorf("failed to deserialize token claims: %w", err)
    }

    if err = validateClaimsWithLeeway(registeredClaims, v.expectedClaims, v.allowedClockSkew); err != nil {
        return nil, fmt.Errorf("expected claims not validated: %w", err)
    }

    if customClaims != nil {
        if err = customClaims.Validate(ctx); err != nil {
            return nil, fmt.Errorf("custom claims not validated: %w", err)
        }
    }

    validatedClaims := &ValidatedClaims{
        RegisteredClaims: RegisteredClaims{
            Issuer:    registeredClaims.Issuer,
            Subject:   registeredClaims.Subject,
            Audience:  registeredClaims.Audience,
            ID:        registeredClaims.ID,
            Expiry:    numericDateToUnixTime(registeredClaims.Expiry),
            NotBefore: numericDateToUnixTime(registeredClaims.NotBefore),
            IssuedAt:  numericDateToUnixTime(registeredClaims.IssuedAt),
        },
        CustomClaims: customClaims,
    }

    return validatedClaims, nil
}

</code>```

could not get token claims: square/go-jose: unsupported key type/format)

Body:
I'm using auth0 and am passing the generated token to the backend for some processing.
I need to validate the token and fetch some data from it (mainly email).

Checking the JWT on jwt.io and it appears valid with all relevant information there.

I'm using the provided auth0 middleware https://github.com/auth0/go-jwt-middleware to parse the token on my end. Everything runs fine until it gets to deserializeClaims.

I'm then hit with: could not get token claims: square/go-jose: unsupported key type/format)

Even just some insight on how to better troubleshoot this would be helpful, as it stands, I have no idea what is wrong.

// ValidateToken validates the passed in JWT using the jose v2 package.
func (v *Validator) ValidateToken(ctx context.Context, tokenString string) (interface{}, error) {
    token, err := jwt.ParseSigned(tokenString)
    if err != nil {
        return nil, fmt.Errorf("could not parse the token: %w", err)
    }

    if err = validateSigningMethod(string(v.signatureAlgorithm), token.Headers[0].Algorithm); err != nil {
        return nil, fmt.Errorf("signing method is invalid: %w", err)
    }

    registeredClaims, customClaims, err := v.deserializeClaims(ctx, token)  <- this fails
    if err != nil {
        return nil, fmt.Errorf("failed to deserialize token claims: %w", err)
    }

    if err = validateClaimsWithLeeway(registeredClaims, v.expectedClaims, v.allowedClockSkew); err != nil {
        return nil, fmt.Errorf("expected claims not validated: %w", err)
    }

    if customClaims != nil {
        if err = customClaims.Validate(ctx); err != nil {
            return nil, fmt.Errorf("custom claims not validated: %w", err)
        }
    }

    validatedClaims := &ValidatedClaims{
        RegisteredClaims: RegisteredClaims{
            Issuer:    registeredClaims.Issuer,
            Subject:   registeredClaims.Subject,
            Audience:  registeredClaims.Audience,
            ID:        registeredClaims.ID,
            Expiry:    numericDateToUnixTime(registeredClaims.Expiry),
            NotBefore: numericDateToUnixTime(registeredClaims.NotBefore),
            IssuedAt:  numericDateToUnixTime(registeredClaims.IssuedAt),
        },
        CustomClaims: customClaims,
    }

    return validatedClaims, nil
}

could not get token claims: square/go-jose: unsupported key type/format)


问:
Which ProductDetail to use to Launch Purchase Flow in PlayBilling v5
I have four subscription products

Monthly subscription (Auto Renew) with Trial Offer

Monthly subscription (Prepaid)

Yearly subscription (Auto Renew) with Trial Offer

Yearly subscription (Prepaid)

After Connection to Google play is established. I query for products available to buy

```<code>val subscriptionProductList = listOf(
            QueryProductDetailsParams.Product.newBuilder()
                .setProductType(BillingClient.ProductType.SUBS)
                .setProductId("premium_sub")
                .build()
        )

val params = QueryProductDetailsParams.newBuilder()
            .setProductList(subscriptionProductList)
            .build()

billingClient.queryProductDetailsAsync(params) {
                billingResult, productDetailsList ->
            val productDetail = productDetailsList[0] // only one subscription product
            val subscriptionOfferDetails = productDetail!!.subscriptionOfferDetails

            for (subscriptionOfferDetail in subscriptionOfferDetails!!){
                Log.d("subscriptionOffer", "------")
                Log.d("subscriptionOffer", subscriptionOfferDetail.offerTags.toString())
                Log.d("subscriptionOffer", subscriptionOfferDetail.offerId.toString())
                Log.d("subscriptionOffer", "------")

            }
        }
</code>```

The method returns, six,  6 ProductDetails.SubscriptionOfferDetails the additional two came from the trial offers, that is one each from auto renew monthly and yearly plan.

If I am going to offer the auto renew monthly subscription which ProductDetails.SubscriptionOfferDetails should I use?

For locales (eg India) that require subscriptions to be prepaid does Google play returns products only valid for specific users?

Body:
I have four subscription products

Monthly subscription (Auto Renew) with Trial Offer

Monthly subscription (Prepaid)

Yearly subscription (Auto Renew) with Trial Offer

Yearly subscription (Prepaid)

After Connection to Google play is established. I query for products available to buy

val subscriptionProductList = listOf(
            QueryProductDetailsParams.Product.newBuilder()
                .setProductType(BillingClient.ProductType.SUBS)
                .setProductId("premium_sub")
                .build()
        )

val params = QueryProductDetailsParams.newBuilder()
            .setProductList(subscriptionProductList)
            .build()

billingClient.queryProductDetailsAsync(params) {
                billingResult, productDetailsList ->
            val productDetail = productDetailsList[0] // only one subscription product
            val subscriptionOfferDetails = productDetail!!.subscriptionOfferDetails

            for (subscriptionOfferDetail in subscriptionOfferDetails!!){
                Log.d("subscriptionOffer", "------")
                Log.d("subscriptionOffer", subscriptionOfferDetail.offerTags.toString())
                Log.d("subscriptionOffer", subscriptionOfferDetail.offerId.toString())
                Log.d("subscriptionOffer", "------")

            }
        }

The method returns, six,  6 ProductDetails.SubscriptionOfferDetails the additional two came from the trial offers, that is one each from auto renew monthly and yearly plan.

If I am going to offer the auto renew monthly subscription which ProductDetails.SubscriptionOfferDetails should I use?

For locales (eg India) that require subscriptions to be prepaid does Google play returns products only valid for specific users?


问:
How to load image from Django content field in Next.js?
I have data coming from the Django API, there is a TextField field, it uses the markdown editor. Loading the text, I get everything except the image.

The reason it won't load is the wrong link because it looks like this: media/uploads/image.jpg
Next.js, in turn, tries to add an address to it, did this: localhost:3000/media/uploads/image.jpg, but localhost:8000/media/uploads/image.jpg will be correct, how to make an absolute link? There are no problems with the preview, everything can be configured there.


问:
Optimal number of threads
I was experimented with multithreading and parallel programming. According to my current knowledge, for intensive cpu computations, the optimal thread number is equal to the number of cores, otherwise u'll have an overhead regarding context switch between threads. I am not involving hyperthreading in the game where you can double the logical processors. I tried to play  with a parallel quicksort on  a 4 core cpu with disabled hyperthreading.

This is a result set that made me a bit curious.

I am a bit confused reading numerous of answers why this can happen.

I can understand that 8 threads have no significant performance, but why they compute faster than 4 threads ?

```<code>CPU Cores : 4

10 tests ran with 1 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 3579
10 tests ran with 2 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 2458
10 tests ran with 4 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1230
10 tests ran with 8 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1030
10 tests ran with 16 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1026
10 tests ran with 32 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1036
10 tests ran with 64 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1094
</code>```

JMH results on 30million sample array with 10 iterations

```<code>Benchmark            Mode  Cnt     Score     Error  Units
Sample.run16Threads  avgt   10  1057.336 ±  38.845  ms/op
Sample.run1Thread    avgt   10  3385.159 ±  15.619  ms/op
Sample.run2Threads   avgt   10  1809.542 ±  23.794  ms/op
Sample.run32Threads  avgt   10  1133.388 ±  86.976  ms/op
Sample.run4Threads   avgt   10  1120.386 ± 113.688  ms/op
Sample.run64Threads  avgt   10  1546.910 ± 488.938  ms/op
Sample.run8Threads   avgt   10  1031.181 ±  52.650  ms/op
</code>```
```<code>public class ParallelQuickSort extends RecursiveAction {
    private final int left;
    private final int right;
    private final int[] arr;

    public ParallelQuickSort(int left, int right, int[] arr) {
        this.left = left;
        this.right = right;
        this.arr = arr;
    }

    private int partition(int[] arr, long pivot) {
        int leftPtr = left - 1;
        int rightPtr = right;

        while ( true ) {
            while ( arr[++leftPtr] < pivot ) ;
            while ( rightPtr > 0 && arr[--rightPtr] > pivot ) ;

            if ( leftPtr >= rightPtr ) {
                break;
            } else {
                swap( arr, leftPtr, rightPtr );
            }
        }
        swap( arr, leftPtr, right );
        return leftPtr;
    }

    private void swap(int[] arr, int x, int y) {
        int temp = arr[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }

    @Override
    protected void compute() {
        if ( right - left <= 0 ) {
            return;
        }
        long pivot = arr[right];
        int partition = partition( arr, pivot );
        ForkJoinTask.invokeAll( createSubTasks( partition ) );
    }

    private List<ParallelQuickSort> createSubTasks(int partition) {
        return List.of(
                new ParallelQuickSort( left, partition - 1, arr ),
                new ParallelQuickSort( partition + 1, right, arr )
        );
    }
}

public class Main {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();
        int[] arr = IntStream.range( 0, 30_000_000 ).map( i -> secureRandom.nextInt( 200_000 ) ).toArray();
        int tests = 10;

        System.out.println( "CPU Cores : " + Runtime.getRuntime().availableProcessors() + "\n" );
        for ( int threads = 1; threads <= 64; threads *= 2 ) {
            long time = 0;
            for ( int i = 0; i < tests; ++i ) {
                int[] sample = Arrays.copyOfRange( arr, 0, arr.length );
                ForkJoinPool forkJoinPool = new ForkJoinPool(threads);
                long start = System.currentTimeMillis();
                forkJoinPool.invoke( new ParallelQuickSort( 0, arr.length - 1, sample ) );
                long end = System.currentTimeMillis();
                forkJoinPool.shutdown();
                time += end - start;
                //System.out.println( isSorted( sample ) );
            }
            System.out.println( tests + " tests ran with " + threads +
                    " thread(s), on an array of size : " + arr.length + ". Sorting process took on avg for each test : " + time / tests );
        }
    }

    private static boolean isSorted(int[] arr) {
        boolean isSorted = true;
        for ( int i = 0; i < arr.length - 1; ++i ) {
            if ( arr[i] > arr[i + 1] ) {
                isSorted = false;
                break;
            }
        }
        return isSorted;
    }
}
</code>```

Title: Optimal number of threads

Body:
I was experimented with multithreading and parallel programming. According to my current knowledge, for intensive cpu computations, the optimal thread number is equal to the number of cores, otherwise u'll have an overhead regarding context switch between threads. I am not involving hyperthreading in the game where you can double the logical processors. I tried to play  with a parallel quicksort on  a 4 core cpu with disabled hyperthreading.

This is a result set that made me a bit curious.

I am a bit confused reading numerous of answers why this can happen.

I can understand that 8 threads have no significant performance, but why they compute faster than 4 threads ?

CPU Cores : 4

10 tests ran with 1 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 3579
10 tests ran with 2 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 2458
10 tests ran with 4 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1230
10 tests ran with 8 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1030
10 tests ran with 16 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1026
10 tests ran with 32 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1036
10 tests ran with 64 thread(s), on an array of size : 30000000. Sorting process took on avg for each test : 1094

JMH results on 30million sample array with 10 iterations

Benchmark            Mode  Cnt     Score     Error  Units
Sample.run16Threads  avgt   10  1057.336 ±  38.845  ms/op
Sample.run1Thread    avgt   10  3385.159 ±  15.619  ms/op
Sample.run2Threads   avgt   10  1809.542 ±  23.794  ms/op
Sample.run32Threads  avgt   10  1133.388 ±  86.976  ms/op
Sample.run4Threads   avgt   10  1120.386 ± 113.688  ms/op
Sample.run64Threads  avgt   10  1546.910 ± 488.938  ms/op
Sample.run8Threads   avgt   10  1031.181 ±  52.650  ms/op

public class ParallelQuickSort extends RecursiveAction {
    private final int left;
    private final int right;
    private final int[] arr;

    public ParallelQuickSort(int left, int right, int[] arr) {
        this.left = left;
        this.right = right;
        this.arr = arr;
    }

    private int partition(int[] arr, long pivot) {
        int leftPtr = left - 1;
        int rightPtr = right;

        while ( true ) {
            while ( arr[++leftPtr] < pivot ) ;
            while ( rightPtr > 0 && arr[--rightPtr] > pivot ) ;

            if ( leftPtr >= rightPtr ) {
                break;
            } else {
                swap( arr, leftPtr, rightPtr );
            }
        }
        swap( arr, leftPtr, right );
        return leftPtr;
    }

    private void swap(int[] arr, int x, int y) {
        int temp = arr[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }

    @Override
    protected void compute() {
        if ( right - left <= 0 ) {
            return;
        }
        long pivot = arr[right];
        int partition = partition( arr, pivot );
        ForkJoinTask.invokeAll( createSubTasks( partition ) );
    }

    private List<ParallelQuickSort> createSubTasks(int partition) {
        return List.of(
                new ParallelQuickSort( left, partition - 1, arr ),
                new ParallelQuickSort( partition + 1, right, arr )
        );
    }
}

public class Main {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();
        int[] arr = IntStream.range( 0, 30_000_000 ).map( i -> secureRandom.nextInt( 200_000 ) ).toArray();
        int tests = 10;

        System.out.println( "CPU Cores : " + Runtime.getRuntime().availableProcessors() + "\n" );
        for ( int threads = 1; threads <= 64; threads *= 2 ) {
            long time = 0;
            for ( int i = 0; i < tests; ++i ) {
                int[] sample = Arrays.copyOfRange( arr, 0, arr.length );
                ForkJoinPool forkJoinPool = new ForkJoinPool(threads);
                long start = System.currentTimeMillis();
                forkJoinPool.invoke( new ParallelQuickSort( 0, arr.length - 1, sample ) );
                long end = System.currentTimeMillis();
                forkJoinPool.shutdown();
                time += end - start;
                //System.out.println( isSorted( sample ) );
            }
            System.out.println( tests + " tests ran with " + threads +
                    " thread(s), on an array of size : " + arr.length + ". Sorting process took on avg for each test : " + time / tests );
        }
    }

    private static boolean isSorted(int[] arr) {
        boolean isSorted = true;
        for ( int i = 0; i < arr.length - 1; ++i ) {
            if ( arr[i] > arr[i + 1] ) {
                isSorted = false;
                break;
            }
        }
        return isSorted;
    }
}


问:
how to pass dynamic value in void() react redux
I want to pass dynamic value in company.</p>
```<code> const getAllEntities = () => {
    dispatch(
      getEntities({
        page: paginationState.activePage - 1,
        size: paginationState.itemsPerPage,
        sort: `${paginationState.sort},${paginationState.order}`,
        company: 'tcs',
      })
    );
  };

export const getEntities = createAsyncThunk('employee/fetch_entity_list', async ({ page, size, sort, company}IQueryParams) => {
  const requestUrl = `${apiUrl}/${"employees-list"}/**${company}**`;
  return axios.get<IEmployee[]>(requestUrl);
});
</code>```

Body:
I want to pass dynamic value in company.

 const getAllEntities = () => {
    dispatch(
      getEntities({
        page: paginationState.activePage - 1,
        size: paginationState.itemsPerPage,
        sort: `${paginationState.sort},${paginationState.order}`,
        company: 'tcs',
      })
    );
  };

export const getEntities = createAsyncThunk('employee/fetch_entity_list', async ({ page, size, sort, company}IQueryParams) => {
  const requestUrl = `${apiUrl}/${"employees-list"}/**${company}**`;
  return axios.get<IEmployee[]>(requestUrl);
});


问:
Loading/security issue when drawing images on a canvas
My question might be stupid, but I'm stuck with a simple task.

I'm writing a web browser game where I load images from a local folder to a 2d canvas, then, at some time, redraw it with getImageData().
The code sample is the following

```<code>let img = new Image()
// img.crossOrigin = "anonymous"
img.src = "assets/hidden.png"

let ctx = document.getElementById("canvas").getContext("2d")

img.onload = () => {
    console.log("loaded img", img.src)
    ctx.drawImage(img, 0, 0)

    let c = ctx.getImageData(0, 0, 10, 10)
}
</code>```

The original problem was that calling getImageData() causes Uncaught DOMException: The operation is insecure.
So I added img.crossOrigin = "anonymous" (context.getImageData() operation is insecure) to overcome this, but now the image is not loaded at all. How do I normally use images in canvas?

Body:
My question might be stupid, but I'm stuck with a simple task.

I'm writing a web browser game where I load images from a local folder to a 2d canvas, then, at some time, redraw it with getImageData().
The code sample is the following

let img = new Image()
// img.crossOrigin = "anonymous"
img.src = "assets/hidden.png"

let ctx = document.getElementById("canvas").getContext("2d")

img.onload = () => {
    console.log("loaded img", img.src)
    ctx.drawImage(img, 0, 0)

    let c = ctx.getImageData(0, 0, 10, 10)
}

The original problem was that calling getImageData() causes Uncaught DOMException: The operation is insecure.
So I added img.crossOrigin = "anonymous" (context.getImageData() operation is insecure) to overcome this, but now the image is not loaded at all. How do I normally use images in canvas?