问:
How can I make a drawing animation with a child of View, drawing each Path's line one by one?
Using the code I found in this StackOverflow answer I successfully can draw anything in a Canvas by finger, and I will see what I draw while I draw it. From this, I want to make a function triggered on button press that will do two things:

Erase what is drawn over the canvas.

Replay whatever picture was drawn over it before canvas was cleared, by redrawing each path's lines one by one at a constant speed.

In order to do so, I have slightly modificated the onTouchEvent code, so it stores each drawn point accordingly:

```<code>@Override
public boolean onTouchEvent(MotionEvent event) {
    StrokePoint point;

    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            mPath.moveTo(event.getX(), event.getY());

            // Retrieve strokes in memory
            stroke_buffer = new Stroke();
            stroke_buffer.points = new ArrayList<StrokePoint>();
            point = new StrokePoint();
            point.x = event.getX();
            point.y = event.getY();
            stroke_buffer.points.add( point );

            break;
        case MotionEvent.ACTION_MOVE:
            mPath.lineTo(event.getX(), event.getY());

            // Retrieve strokes in memory
            point = new StrokePoint();
            point.x = event.getX();
            point.y = event.getY();
            stroke_buffer.points.add( point );

            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            // Retrieve strokes in memory
            strokes.add(stroke_buffer);
            break;
        default:
            break;
    }
    return true;
}
</code>```

That way, I can load the X and Y points later in loops (that's the idea at least). The problem is I am not sure how to trigger the "redraw" on the canvas for each line. I tried to store the canvas from the "onDraw" like this:

```<code>@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(mPath, mPaint);

    // For trying to make the "redraw" later
    this.mCanvas = canvas;

    super.onDraw(canvas);
}
</code>```

And then, I make this method for the button which I want to erase and replay the previously drawn strokes:

```<code>public void replayStrokes() {
    // I start a new path from scratch ad-hoc the "redraw" animation.
    mPath = new Path();
    Log.i("SANDBOX_INFO", "Button pressed");
    // Intention here is leaving the "whiteboard" clear again.
    mCanvas.drawRGB(255, 255, 255);
    invalidate();
    this.draw(mCanvas);
    SystemClock.sleep(1000);

    // Redraw "line by line" loop
    mPath.moveTo(strokes.get(0).points.get(0).x,
                 strokes.get(0).points.get(0).y);
    for (int i = 0; i < strokes.size(); i++) {
        for (int j = 0; j < strokes.get(i).points.size(); j++) {
            if (i == 0 && j == 0) continue;
            mPath.lineTo(strokes.get(i).points.get(j).x,
                         strokes.get(i).points.get(j).y);
            mCanvas.drawPath(mPath, mPaint);
            invalidate();
            this.draw(mCanvas);
            SystemClock.sleep(100);
        }
    }
}
</code>```

When I press the button, the method replayStrokes doesn't behave as expected. It's like it remains "thinking" (processing) and, when you least expect it, refreshes all the changes in a single blow; instead, I want it to be a smooth animation where you can see the entire Path previously drawn by finger, replayed line by line, point by point. What am I doing wrong? What should I change to obtain the expected behaviour?

答:
I ended up figuring out a solution thanks to @VitorHugoSchwaab 's comment. Little reminder: all the code I have posted in this question is supposed to be inside a public class DrawCanvas extends View class. That said:

So, i left the "trigger method" like this:

```<code>private int s, p;
private boolean replay_mode;

public void replayStrokes() {
    s = 0;
    p = 0;
    replay_mode = true;
    invalidate();
}
</code>```

And I modified the onDraw method like this (I transformed it into a Megamoth, but that I can fix later :P) :

```<code>@Override
protected void onDraw(Canvas canvas) {
    if (replay_mode) {
        if (s == 0 && p == 0) {
            Log.i("SANDBOX_INFO", "Replay Mode START");
            canvas.drawRGB(255, 255, 255);
            p++;
            replayPath.reset();
            replayPath.moveTo(strokes.get(0).points.get(0).x,
                    strokes.get(0).points.get(0).y);
            invalidate();
        } else {
            Log.i("SANDBOX_INFO", "Replaying --> S:" + s + " P:" + p);
            if (p == 0) {
                replayPath.moveTo(strokes.get(s).points.get(p).x,
                        strokes.get(s).points.get(p).y);
            } else {
                replayPath.lineTo(strokes.get(s).points.get(p).x,
                        strokes.get(s).points.get(p).y);
                canvas.drawPath(replayPath, mPaint);
            }

            int points_size = strokes.get(s).points.size();
            if (s == strokes.size() - 1 && p == points_size - 1) {
                Log.i("SANDBOX_INFO", "Replay Mode END");
                replay_mode = false;
            }
            else if (p == points_size - 1) {
                s++;
                p = 0;
            } else {
                p++;
            }
        }
        invalidate();
    } else {
        canvas.drawPath(mPath, mPaint);
    }

    super.onDraw(canvas);
}
</code>```

This works. However, there's a glitchy effect of "flashing" while the strokes are replayed. I think that might be because it's actually "redrawing" the entire "replay path" on every frame. Based on this guess, I will try to workaround the issue when I have somemore time to code.

Body:
Using the code I found in this StackOverflow answer I successfully can draw anything in a Canvas by finger, and I will see what I draw while I draw it. From this, I want to make a function triggered on button press that will do two things:

Erase what is drawn over the canvas.

Replay whatever picture was drawn over it before canvas was cleared, by redrawing each path's lines one by one at a constant speed.

In order to do so, I have slightly modificated the onTouchEvent code, so it stores each drawn point accordingly:

@Override
public boolean onTouchEvent(MotionEvent event) {
    StrokePoint point;

    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            mPath.moveTo(event.getX(), event.getY());

            // Retrieve strokes in memory
            stroke_buffer = new Stroke();
            stroke_buffer.points = new ArrayList<StrokePoint>();
            point = new StrokePoint();
            point.x = event.getX();
            point.y = event.getY();
            stroke_buffer.points.add( point );

            break;
        case MotionEvent.ACTION_MOVE:
            mPath.lineTo(event.getX(), event.getY());

            // Retrieve strokes in memory
            point = new StrokePoint();
            point.x = event.getX();
            point.y = event.getY();
            stroke_buffer.points.add( point );

            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            // Retrieve strokes in memory
            strokes.add(stroke_buffer);
            break;
        default:
            break;
    }
    return true;
}

That way, I can load the X and Y points later in loops (that's the idea at least). The problem is I am not sure how to trigger the "redraw" on the canvas for each line. I tried to store the canvas from the "onDraw" like this:

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(mPath, mPaint);

    // For trying to make the "redraw" later
    this.mCanvas = canvas;

    super.onDraw(canvas);
}

And then, I make this method for the button which I want to erase and replay the previously drawn strokes:

public void replayStrokes() {
    // I start a new path from scratch ad-hoc the "redraw" animation.
    mPath = new Path();
    Log.i("SANDBOX_INFO", "Button pressed");
    // Intention here is leaving the "whiteboard" clear again.
    mCanvas.drawRGB(255, 255, 255);
    invalidate();
    this.draw(mCanvas);
    SystemClock.sleep(1000);

    // Redraw "line by line" loop
    mPath.moveTo(strokes.get(0).points.get(0).x,
                 strokes.get(0).points.get(0).y);
    for (int i = 0; i < strokes.size(); i++) {
        for (int j = 0; j < strokes.get(i).points.size(); j++) {
            if (i == 0 && j == 0) continue;
            mPath.lineTo(strokes.get(i).points.get(j).x,
                         strokes.get(i).points.get(j).y);
            mCanvas.drawPath(mPath, mPaint);
            invalidate();
            this.draw(mCanvas);
            SystemClock.sleep(100);
        }
    }
}

When I press the button, the method replayStrokes doesn't behave as expected. It's like it remains "thinking" (processing) and, when you least expect it, refreshes all the changes in a single blow; instead, I want it to be a smooth animation where you can see the entire Path previously drawn by finger, replayed line by line, point by point. What am I doing wrong? What should I change to obtain the expected behaviour?

Body:
I ended up figuring out a solution thanks to @VitorHugoSchwaab 's comment. Little reminder: all the code I have posted in this question is supposed to be inside a public class DrawCanvas extends View class. That said:

So, i left the "trigger method" like this:

private int s, p;
private boolean replay_mode;

public void replayStrokes() {
    s = 0;
    p = 0;
    replay_mode = true;
    invalidate();
}

And I modified the onDraw method like this (I transformed it into a Megamoth, but that I can fix later :P) :

@Override
protected void onDraw(Canvas canvas) {
    if (replay_mode) {
        if (s == 0 && p == 0) {
            Log.i("SANDBOX_INFO", "Replay Mode START");
            canvas.drawRGB(255, 255, 255);
            p++;
            replayPath.reset();
            replayPath.moveTo(strokes.get(0).points.get(0).x,
                    strokes.get(0).points.get(0).y);
            invalidate();
        } else {
            Log.i("SANDBOX_INFO", "Replaying --> S:" + s + " P:" + p);
            if (p == 0) {
                replayPath.moveTo(strokes.get(s).points.get(p).x,
                        strokes.get(s).points.get(p).y);
            } else {
                replayPath.lineTo(strokes.get(s).points.get(p).x,
                        strokes.get(s).points.get(p).y);
                canvas.drawPath(replayPath, mPaint);
            }

            int points_size = strokes.get(s).points.size();
            if (s == strokes.size() - 1 && p == points_size - 1) {
                Log.i("SANDBOX_INFO", "Replay Mode END");
                replay_mode = false;
            }
            else if (p == points_size - 1) {
                s++;
                p = 0;
            } else {
                p++;
            }
        }
        invalidate();
    } else {
        canvas.drawPath(mPath, mPaint);
    }

    super.onDraw(canvas);
}

This works. However, there's a glitchy effect of "flashing" while the strokes are replayed. I think that might be because it's actually "redrawing" the entire "replay path" on every frame. Based on this guess, I will try to workaround the issue when I have somemore time to code.


来源: stackexchange

问:
Initializing from a pair in constructur intializer list
I have a function f returning a pair of objects of classes A and B:

```<code>auto f() -> std::pair<A,B>;
</code>```

Furthermore, I have a class C that has A and B as members:

```<code>class C {
  public:
    C();
  private:
    A a;
    B b;
};
</code>```

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

```<code>C(): a(f().first), b(f().second) {}
</code>```

This calls f twice though and it is a quite complicated function.
Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

答:
One possible solution:

```<code>class C {
  public:
    C(std::pair<A,B>);
  private:
    ...
};

C(pair<A,B> p): a(p.first), b(p.second) {}
</code>```

You'll now call f only once, which will work so long as it doesn't contradict some other requirements.

ContentLicense: CC BY-SA 4.0

Body:
I have a function f returning a pair of objects of classes A and B:

auto f() -> std::pair;

Furthermore, I have a class C that has A and B as members:

class C {
  public:
    C();
  private:
    A a;
    B b;
};

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

C(): a(f().first), b(f().second) {}

This calls f twice though and it is a quite complicated function.
Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

Body:
One possible solution:

class C {
  public:
    C(std::pair<A,B>);
  private:
    ...
};

C(pair<A,B> p): a(p.first), b(p.second) {}

You'll now call f only once, which will work so long as it doesn't contradict some other requirements.


问:
What's most performant way in iOS to check if a string is one of a list of strings?
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

```<code>- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}
</code>```

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.

答:
```<code>- (BOOL)isString:(NSString *)testString inList:(NSString *)spaceSeparatedStrings
{
    NSArray *list = [spaceSeparatedStrings componentsSeparatedByString:@" "];
    return [list containsObject:testString];
}
</code>```

Note: the above will be case-sensative, unlike your example.  For case-insensative, you will probably have to iterate over some portion of the NSArray.

ContentLicense: CC BY-SA 3.0

Body:
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.

Body:
- (BOOL)isString:(NSString *)testString inList:(NSString *)spaceSeparatedStrings
{
    NSArray *list = [spaceSeparatedStrings componentsSeparatedByString:@" "];
    return [list containsObject:testString];
}

Note: the above will be case-sensative, unlike your example.  For case-insensative, you will probably have to iterate over some portion of the NSArray.


问:
Docker desktop on Mac doesn't bring up nginx home page with Kubernetes
I am using k8s on Docker desktop on Mac. I have applied the below yaml file and the deployment got success. But when I access "localhost:8888", I get page not found and can't see nginx default homepage. (images attached)</p>
```<code>kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      app: my-nginx
  template:
    metadata:
      labels:
        app: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 80

---

apiVersion: v1
kind: Service
metadata:
  name: my-nginx-np
spec:
  type: NodePort
  selector:
    app: my-nginx-np
  ports:
  - port: 8888
    targetPort: 80```

[enter image description here][1]

[enter image description here][2]

  [1]: https://i.stack.imgur.com/edbG9.png
  [2]: https://i.stack.imgur.com/Ak6UZ.png
</code>```

答:
Your service is not pointing to the Nginx deployment (you are using the wrong selectors). Try to use the following service</p>
```<code>apiVersion: v1
kind: Service
metadata:
  name: my-nginx-np
spec:
  type: NodePort
  selector:
    app: my-nginx
  ports:
  - port: 8888
    targetPort: 80
</code>```

Body:
I am using k8s on Docker desktop on Mac. I have applied the below yaml file and the deployment got success. But when I access "localhost:8888", I get page not found and can't see nginx default homepage. (images attached)

kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      app: my-nginx
  template:
    metadata:
      labels:
        app: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 80

---

apiVersion: v1
kind: Service
metadata:
  name: my-nginx-np
spec:
  type: NodePort
  selector:
    app: my-nginx-np
  ports:
  - port: 8888
    targetPort: 80```

[enter image description here][1]

[enter image description here][2]

  [1]: https://i.stack.imgur.com/edbG9.png
  [2]: https://i.stack.imgur.com/Ak6UZ.png

Body:
Your service is not pointing to the Nginx deployment (you are using the wrong selectors). Try to use the following service

apiVersion: v1
kind: Service
metadata:
  name: my-nginx-np
spec:
  type: NodePort
  selector:
    app: my-nginx
  ports:
  - port: 8888
    targetPort: 80


问:
SQL select instance in table if it does no longer exist with later year value
The following table structure is given:

year
team_ID
team

2011
1
Manchester

2011
2
Bayern

2011
3
Madrid

2012
1
Manchester

2012
2
Bayern

2012
4
Chelsea

The Objective is to select the teams that were in the table in the year 2011 but got kicked out for the year 2012.
In this case only Madrid has the year 2011 but not 2012, so it would be the only one selected.

The expected output is:

team

Madrid

Thank you for your help!

答:
You should use a correlated exists, such as

```<code>select team
from t
where year=2011
and not exists (select * from t t2 where t2.year = 2012 and t2.team = t.team);
</code>```

Body:
You should use a correlated exists, such as

select team
from t
where year=2011
and not exists (select * from t t2 where t2.year = 2012 and t2.team = t.team);


问:
SVN notification when a specific file in the repository changes
Is there a way to configure SVN to send me email when a specific file in the repository changes?</p>

答:
You would probably want to write a post commit hook for your repository.

There are plenty of examples of that if you do a search for it.


问:
Set one kind of enum to another enum kind of enum in java
I have identical enums defined in both an entity class as well as in a response class. I want to set the value of an enum property in one of the classes to an enum property from the other class. Below is sample code.  I am very new to Java and the IT industry.

@Getter
@Setter
public class ResponseClass{
    enum Type{
        USD, CSD, MXN, BRL;
    };

    private Type type;
}
```
<pre class="lang-java prettyprint-override"><code>@Entity
@Getter
@Setter
public class EntityClass{
    enum Type{
        USD, CSD, MXN, BRL;
    };

    @Column(name = "type")
    private Type type;
}
</code>```

public class Main{
    public static void main(){
        EntityClass entity= new EntityClass();

        ResponseClass response = ...; //Got value for this variable from REST API

        entity.setType(response.getType()); // I want to achive this
    }
}
```

答:
It would be better if you declare enum Type out of Entity or Response class. Then you could use same enum for both classes.

You can declare an enum at any of three levels:

Separate class

Nested within a class

Locally (in Java 16+)

For your situation, I suggest you use the first rather than the second.

Body:
I have identical enums defined in both an entity class as well as in a response class. I want to set the value of an enum property in one of the classes to an enum property from the other class. Below is sample code.  I am very new to Java and the IT industry.

@Getter
@Setter
public class ResponseClass{
    enum Type{
        USD, CSD, MXN, BRL;
    };

    private Type type;
}

@Entity
@Getter
@Setter
public class EntityClass{
    enum Type{
        USD, CSD, MXN, BRL;
    };

    @Column(name = "type")
    private Type type;
}

public class Main{
    public static void main(){
        EntityClass entity= new EntityClass();

        ResponseClass response = ...; //Got value for this variable from REST API

        entity.setType(response.getType()); // I want to achive this
    }
}


问:
Angular/RxJs - Calling next() on Observable in service after component was unsubscribe() cause ObjectUnsubscribedError
I have an Angular Service that defines a public Subject. Later under some condition, the service will call .next() on this Subject.

In addition, I have an Angular component that .subscribe() to this Subject in it's ngOnInit() method, and call .unsubscribe() in it's ngOnDestroy() method.

While both the service and the component are alive my code works fine. However, the user can click on a different tab in my app. Which cause my component to unload and call its ngOnDestroy() method, meaning the Observable was unsubscribed.

Starting from this point, the component no longer exists however the service is still alive - other components still use it. When the service calling .next() method after the component called .unsubscribe(), this error is thrown ObjectUnsubscribedError.
ERROR Error: Uncaught (in promise): ObjectUnsubscribedError: object unsubscribed

In addition, later if the user goes back to the tab that contains the component, the ngOnInit() is executed and the re-subscription to this observable throws the same error again.

What am I doing wrong, how can I resolve these errors?

```<code>import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class StatusService {
  public statusChange$: Subject<number>;

  public constructor(...) {
    this.statusChange$ = new Subject<number>();
  }

  public someInternalLogic(someNumber: number): void {
    this.statusChange$.next(someNumber);
    // this will throw an error if StatusComponent call .unsubscribe()
  }
}

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.scss']
})
export class StatusComponent implements OnInit, OnDestroy {
  public constructor(
    private _statusService: StatusService) {}

    public ngOnInit(): void {
      this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
  }

  public ngOnDestroy(): void {
    this._statusService.statusChange$.unsubscribe();
    // after this point if the StatusService calling .next() an error will be thrown
  }

  private _onStatusChange(value: number): void {
    // ....
  }
}

</code>```

答:
You don't need to unsubscribe service subject in component. Instead create an subscription variable for service subject in your component and unsubscribe it on component destroy</p>
```<code>subscription!: Subscription;

public ngOnInit(): void {
    this.subscription = this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
}

public ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

private _onStatusChange(value: number): void {
    // ....
}
</code>```

Body:
I have an Angular Service that defines a public Subject. Later under some condition, the service will call .next() on this Subject.

In addition, I have an Angular component that .subscribe() to this Subject in it's ngOnInit() method, and call .unsubscribe() in it's ngOnDestroy() method.

While both the service and the component are alive my code works fine. However, the user can click on a different tab in my app. Which cause my component to unload and call its ngOnDestroy() method, meaning the Observable was unsubscribed.

Starting from this point, the component no longer exists however the service is still alive - other components still use it. When the service calling .next() method after the component called .unsubscribe(), this error is thrown ObjectUnsubscribedError.
ERROR Error: Uncaught (in promise): ObjectUnsubscribedError: object unsubscribed

In addition, later if the user goes back to the tab that contains the component, the ngOnInit() is executed and the re-subscription to this observable throws the same error again.

What am I doing wrong, how can I resolve these errors?

import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class StatusService {
  public statusChange$: Subject<number>;

  public constructor(...) {
    this.statusChange$ = new Subject<number>();
  }

  public someInternalLogic(someNumber: number): void {
    this.statusChange$.next(someNumber);
    // this will throw an error if StatusComponent call .unsubscribe()
  }
}

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.scss']
})
export class StatusComponent implements OnInit, OnDestroy {
  public constructor(
    private _statusService: StatusService) {}

    public ngOnInit(): void {
      this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
  }

  public ngOnDestroy(): void {
    this._statusService.statusChange$.unsubscribe();
    // after this point if the StatusService calling .next() an error will be thrown
  }

  private _onStatusChange(value: number): void {
    // ....
  }
}

Body:
You don't need to unsubscribe service subject in component. Instead create an subscription variable for service subject in your component and unsubscribe it on component destroy

subscription!: Subscription;

public ngOnInit(): void {
    this.subscription = this._statusService.statusChange$.subscribe(value => this._onStatusChange(value));
}

public ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

private _onStatusChange(value: number): void {
    // ....
}


问:
SSH and identity file for jump server
I'm trying to log into my-server through a jump server, jump.example.com.

I can successfully log into the jump server without a password request:

ssh -i .ssh/id_rsa user@jump.example.com
```
<p>But if I use</p>
<pre class="lang-sh prettyprint-override"><code>ssh -i .ssh/id_rsa -o ProxyCommand="ssh -W %h:%p user@jump.example.com" user@my-server
# or
ssh -i .ssh/id_rsa -J user@jump.example.com user@my-server
</code>```

I'm prompted for a password for user@jump.example.com.
I would not be surprised if I would prompted for a password for user@my-server instead.

How can I specify an identity file for the jump server?

答:
I would suggest to add the following to your ssh config

```<code>Host my_server
        Hostname my-server
        ProxyCommand ssh -W %h:%p jump_server
        User user
        IdentityFile path/to/ssh/identity/file
        Port 22

Host jump_server
        Hostname jump.example.com
        User user
        IdentityFile path/to/ssh/identity/file
        Port 22

</code>```

Finally to connect to your target server use

```<code>ssh my_server
</code>```

Title: SSH and identity file for jump server

Body:
I'm trying to log into my-server through a jump server, jump.example.com.

I can successfully log into the jump server without a password request:

ssh -i .ssh/id_rsa user@jump.example.com

But if I use

ssh -i .ssh/id_rsa -o ProxyCommand="ssh -W %h:%p user@jump.example.com" user@my-server
# or
ssh -i .ssh/id_rsa -J user@jump.example.com user@my-server

I'm prompted for a password for user@jump.example.com.
I would not be surprised if I would prompted for a password for user@my-server instead.

How can I specify an identity file for the jump server?

Body:
I would suggest to add the following to your ssh config

Host my_server
        Hostname my-server
        ProxyCommand ssh -W %h:%p jump_server
        User user
        IdentityFile path/to/ssh/identity/file
        Port 22

Host jump_server
        Hostname jump.example.com
        User user
        IdentityFile path/to/ssh/identity/file
        Port 22

Finally to connect to your target server use

ssh my_server


问:
Finding Pivot element in a sorted array, How do I optimize this code?
Is there a way to optimize this code?
I'm trying to find an element in the list where the sorted list is rotated. [8,9,10,11,12,6,7] Here the element I'm trying to find is 6 with an index 5.</p>
```<code>class Solution:
    def search(self, nums: List[int]) -> int:
        lenn = len(nums)-1
        pivot, mid = 0, (0 + lenn)//2

        if(nums[0] > nums[lenn]):
            while True:
                if(nums[mid] > nums[mid+1]):
                    pivot = mid+1
                    break
                if(nums[mid] < nums[mid-1]):
                    pivot = mid
                    break
                if(nums[mid] > nums[lenn]):
                    mid += 1
                if(nums[mid] < nums[lenn]):
                    mid -= 1
        return pivot
</code>```

答:
Your solution is fast for small lists but not for big ones as it perform a linear-time search. To be faster, you can use a binary search. To do that, you need to use a keep a [start;end] range of values that contains the "pivot". You just need to take the middle item and find which part (left or right) contains increasing items.

Moreover, you can micro-optimize the code. The default implementation of Python is CPython which is a slow interpreter. It optimize almost nothing compared to compilers (of languages like C, Java, Rust) so you should do the optimizations yourself if you want a fast code.  The idea is to use a linear search for few items and a binary search for many ones, and to store values in temporary variables not to compute them twice.

Here is the resulting implementation:

def search(nums):
    first, last = nums[0], nums[-1]

    # Trivial case
    if first <= last:
        return 0

    lenn = len(nums)-1

    # Micro-optimized fast linear search for few items (optional)
    if lenn < 10:
        pivot, mid = 0, lenn//2
        while True:
            middle = nums[mid]
            if middle > nums[mid+1]:
                return mid+1
            elif middle < nums[mid-1]:
                return mid
            elif middle > last:
                mid += 1
            elif middle < last:
                mid -= 1

    # Binary search for many items
    start, end = 0, lenn
    while start+1 < end:
        mid = (start + end) // 2
        midVal = nums[mid]
        if midVal < nums[start]:
            end = mid
        elif midVal > nums[end]:
            start = mid
        else:
            assert False
    return start+1
```

Body:
Is there a way to optimize this code?
I'm trying to find an element in the list where the sorted list is rotated. [8,9,10,11,12,6,7] Here the element I'm trying to find is 6 with an index 5.

class Solution:
    def search(self, nums: List[int]) -> int:
        lenn = len(nums)-1
        pivot, mid = 0, (0 + lenn)//2

        if(nums[0] > nums[lenn]):
            while True:
                if(nums[mid] > nums[mid+1]):
                    pivot = mid+1
                    break
                if(nums[mid] < nums[mid-1]):
                    pivot = mid
                    break
                if(nums[mid] > nums[lenn]):
                    mid += 1
                if(nums[mid] < nums[lenn]):
                    mid -= 1
        return pivot


问:
I am getting error while converting my next js project to docker
I'm trying to convert my Next js project to Docker. The Dockerfile I got from the next js github page worked fine for me and I got a build successfully.

```<code># Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
# COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]
</code>```

I wrote this later.

```<code>docker run -p 3000:3000 imagename
</code>```

Then I faced such error and I can't solve it.

```<code>node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
</code>```

I searched a lot on the internet but couldn't find much. What do you think I should do?

答:
TL;DR

My next is version 11, with-docker example is version 12.

I've looked at the history of the Dockerfile in the official Next.js with-docker example. There I've noticed the addition of these lines to the Dockerfile, and the addition of experimental flag outputStandalone.

This flag is available from next@12 while my project is next@11, so undoing these lines in my Dockerfile solved the issue.

Going over that file history can give insight on different issues.

Body:
I'm trying to convert my Next js project to Docker. The Dockerfile I got from the next js github page worked fine for me and I got a build successfully.

# Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
# COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]

I wrote this later.

docker run -p 3000:3000 imagename

Then I faced such error and I can't solve it.

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

I searched a lot on the internet but couldn't find much. What do you think I should do?


问:
How can I get multiple nth elements in a list?
I want to know how I can get multiple elements in a list in one function

for example if I wanted to get elements 1 2 3 and 4 from list a, I would have to type a!!0 ++ a!!1 ++ a!!2 ++ a!!3. This takes up a lot of space especially if the list name is more than one character. so I'm wondering if I can do something like a!![0,1,2,3] instead and get all of those elements in a much shorter way. Thank you.

答:
You can work with a mapping where you lookup all items for a list, so:

```<code>map (a !!) [0,1,2,3]
</code>```

If you are however interested in the first four items, you can work with take :: Int  -> [a] -> [a]:

```<code><strong>take 4</strong> a</code>```

especially since looking up by an index (with (!!)) is not a common operation in Haskell: this is unsafe since it is not guaranteed that the index is in bounds. Most list processing is done with functions like take, drop, sum, foldr, etc.

Body:
You can work with a mapping where you lookup all items for a list, so:

map (a !!) [0,1,2,3]

If you are however interested in the first four items, you can work with take :: Int  -> [a] -> [a]:

take 4 a

especially since looking up by an index (with (!!)) is not a common operation in Haskell: this is unsafe since it is not guaranteed that the index is in bounds. Most list processing is done with functions like take, drop, sum, foldr, etc.


问:
Coil don't load image in emulator with Jetpack Compose
I need to show an image in my app by url using Coil, but this image don't load. I follow the official documentation https://coil-kt.github.io/coil/compose/.

profile card

```<code>implementation "io.coil-kt:coil-compose:1.3.1"
</code>```

@Composable
fun ProfilePicture(profilePicture: String, online: Boolean) {
    Card(
        shape = CircleShape,
        border = BorderStroke(
            width = 2.dp,
            color = if (online) MaterialTheme.colors.lightGreen else Color.Red
        ),
        modifier = Modifier.padding(16.dp),
        elevation = 4.dp
    ) {
        Image(
            painter = rememberImagePainter(
                data = profilePicture,
                builder = {
                    transformations(CircleCropTransformation())
                }
            ),
            modifier = Modifier.size(72.dp),
            contentDescription = "Profile picture"
        )
    }
}
```
<p>Update</p>
<p>An exemplo to UserModel</p>
```UserModel(
    name = "John Doe",
    profilePicture = "https://randomuser.me/api/portraits/men/32.jpg",
    online = true
)
```

答:
Check your date/time on the emulator.

The problem might be caused by the fact that Android emulator seems to not synchronize date and time with the network. This makes the emulator certificate appear as expired and leads to the server refusing connection.

After setting the emulator time/date manually to the current one, downloading images started working for me.

Also cold booting the emulator might help (looks like booting from a saved image for some reason sets the date/time to the one from when the image was saved).

Body:
I need to show an image in my app by url using Coil, but this image don't load. I follow the official documentation https://coil-kt.github.io/coil/compose/.

profile card

implementation "io.coil-kt:coil-compose:1.3.1"

@Composable
fun ProfilePicture(profilePicture: String, online: Boolean) {
    Card(
        shape = CircleShape,
        border = BorderStroke(
            width = 2.dp,
            color = if (online) MaterialTheme.colors.lightGreen else Color.Red
        ),
        modifier = Modifier.padding(16.dp),
        elevation = 4.dp
    ) {
        Image(
            painter = rememberImagePainter(
                data = profilePicture,
                builder = {
                    transformations(CircleCropTransformation())
                }
            ),
            modifier = Modifier.size(72.dp),
            contentDescription = "Profile picture"
        )
    }
}

Update

An exemplo to UserModel

UserModel(
    name = "John Doe",
    profilePicture = "https://randomuser.me/api/portraits/men/32.jpg",
    online = true
)


问:
ValueError: Cannot assign "": "Message.name" must be a "CustomUser" instance
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels.

template where the data comes from:

```<code>const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
        )

        chatSocket.onmessage = function(e) {
            console.log(e);

            const data = JSON.parse(e.data)

            if(data.message) {
                document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + ': </b>' + data.message + '<br>')
            } else {
                alert('Empty!')
            }

        }

        chatSocket.onclose = function(e) {
            console.log('The socket closed unexpectedly');
        }

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input')
            const message = messageInputDom.value

            chatSocket.send(JSON.stringify({
                'message': message,
                'name': {{request.user}},
            }))

            messageInputDom.value = ''
        }
</code>```

code used for saving into database in consumers.py

```<code>def save_message(self, name, message):
        Message.objects.create(name=name, content=message)
</code>```

models.py

```<code>from django.db import models

from django.contrib.auth.models import AbstractUser

from .managers import CustomUserManager

# Create your models here.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)

    name = models.CharField(max_length=200, unique=True)

    steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id')
    player = models.TextField(null=True)
    user_coins = models.FloatField(default=0.00)

    is_active = models.BooleanField(default=True, db_column='status')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = "name"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

class Message(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)
</code>```

答:
You can't just pass a string and reference it to an object of CustomUser class. You'll have to pass an instance of it.
First get the relevant instance by using id or a suitable unique attribute,(hope the name is unique)

```<code>def get_object(self, name):
    return CustomUser.objects.get(name=name)
</code>```

And then pass it in your save_message(self, name, message) method,

```<code>def save_message(self, name, message):
    user_obj = self.get_object(name)
    Message.objects.create(name=user_obj, content=message)
</code>```

Body:
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels.

template where the data comes from:

const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
        )

        chatSocket.onmessage = function(e) {
            console.log(e);

            const data = JSON.parse(e.data)

            if(data.message) {
                document.querySelector('#chat-messages').innerHTML += ('' + data.username + ': ' + data.message + '
')
            } else {
                alert('Empty!')
            }

        }

        chatSocket.onclose = function(e) {
            console.log('The socket closed unexpectedly');
        }

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input')
            const message = messageInputDom.value

            chatSocket.send(JSON.stringify({
                'message': message,
                'name': {{request.user}},
            }))

            messageInputDom.value = ''
        }

code used for saving into database in consumers.py

def save_message(self, name, message):
        Message.objects.create(name=name, content=message)

models.py

from django.db import models

from django.contrib.auth.models import AbstractUser

from .managers import CustomUserManager

# Create your models here.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)

    name = models.CharField(max_length=200, unique=True)

    steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id')
    player = models.TextField(null=True)
    user_coins = models.FloatField(default=0.00)

    is_active = models.BooleanField(default=True, db_column='status')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = "name"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

class Message(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)

Body:
You can't just pass a string and reference it to an object of CustomUser class. You'll have to pass an instance of it.
First get the relevant instance by using id or a suitable unique attribute,(hope the name is unique)

def get_object(self, name):
    return CustomUser.objects.get(name=name)

And then pass it in your save_message(self, name, message) method,

def save_message(self, name, message):
    user_obj = self.get_object(name)
    Message.objects.create(name=user_obj, content=message)


问:
In django-forms, how can I make the values of 'name' column of foreign database visible in the selection choices
My Django site has a database model named Status with:

```<code> class Status(models.Model):
     x = models.ForeignKey(Person, on_delete=models.SET_NULL, null = True)
</code>```

The Person database model referenced here contains attributes such as name, profile_pic etc.

In forms.py, I have:

```<code>class StatusForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StatusForm, self).__init__(*args, **kwargs)

    class Meta:
            model = Status
            fields = ['x']
</code>```

Now, when running the site, I get:

I want the name attribute of the Person to be shown in the choices instead of being shown Person object(1), Person object (2).....

How can I make that happen?

答:
In your Person model just add the str method as following:

```<code>class Person(models.Model):
    # Your fields here

    def __str__(self):
        return self.name
</code>```

That will return the name for every instance in the choicefield.

Body:
My Django site has a database model named Status with:

 class Status(models.Model):
     x = models.ForeignKey(Person, on_delete=models.SET_NULL, null = True)

The Person database model referenced here contains attributes such as name, profile_pic etc.

In forms.py, I have:

class StatusForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StatusForm, self).__init__(*args, **kwargs)

    class Meta:
            model = Status
            fields = ['x']

Now, when running the site, I get:

I want the name attribute of the Person to be shown in the choices instead of being shown Person object(1), Person object (2).....

How can I make that happen?

Body:
In your Person model just add the str method as following:

class Person(models.Model):
    # Your fields here

    def __str__(self):
        return self.name

That will return the name for every instance in the choicefield.


问:
How to get the correct data type with date in sql?
The requirements

first_date  The first date the soloist ever performed with the orchestra, in the format '01 Jan 2015' (i.e., month as an integer, short month name, and year as an integer).

last_date   The last date the soloist ever performed with the orchestra, in the format '01 Jan 2015' (i.e., month as an integer, short month name, and year as an integer).

This is my code

```<code> SELECT
    To_char(min(date)::date, 'MM Mon YYYY') as first_date,
    To_char(max(date)::date, 'MM Mon YYYY') as last_date,
 FROM soloists join concerts using (id) limit 4
</code>```

This is the output. The visual output is exactly what I want, but I don't know if it fulfils the data type requirement above. Please help me, thank you.

```<code>first_date       last_date
10 Oct 1980      01 Jan 2014
11 Nov 1979      12 Dec 2011
01 Jan 1980      11 Nov 2015
10 Oct 1961      06 Jun 2009
</code>```

答:
Function to_char return your date type on the text type and on your wanted format. If you need separately year and day on the integer type, then you can use extract function. Example:

```<code>select
    extract(day from min(date)) as first_day,
    extract(year from min(date)) as first_year,
    To_char(min(date), 'Mon') as first_month
from soloists join concerts using (id) limit 4
</code>```

On the result data fields first_day and first_year are will integer types.

Body:
The requirements

first_date  The first date the soloist ever performed with the orchestra, in the format '01 Jan 2015' (i.e., month as an integer, short month name, and year as an integer).

last_date   The last date the soloist ever performed with the orchestra, in the format '01 Jan 2015' (i.e., month as an integer, short month name, and year as an integer).

This is my code

 SELECT
    To_char(min(date)::date, 'MM Mon YYYY') as first_date,
    To_char(max(date)::date, 'MM Mon YYYY') as last_date,
 FROM soloists join concerts using (id) limit 4

This is the output. The visual output is exactly what I want, but I don't know if it fulfils the data type requirement above. Please help me, thank you.

first_date       last_date
10 Oct 1980      01 Jan 2014
11 Nov 1979      12 Dec 2011
01 Jan 1980      11 Nov 2015
10 Oct 1961      06 Jun 2009

Body:
Function to_char return your date type on the text type and on your wanted format. If you need separately year and day on the integer type, then you can use extract function. Example:

select
    extract(day from min(date)) as first_day,
    extract(year from min(date)) as first_year,
    To_char(min(date), 'Mon') as first_month
from soloists join concerts using (id) limit 4

On the result data fields first_day and first_year are will integer types.


问:
How can I pass data between a statefulwidget children to his parent in Flutter/Dart
I want pass the boolean _isSwitched from SetAvailableSwitch class to AvailableScreen class

But actually I can't retrieve the boolean in AvailableScreen class. And as you can see SetAvailableSwitch class is in the Widget build of AvailableScreen class so I don't know how to do that.

AvailableScreen class :

```<code>class AvailableScreen extends StatefulWidget
{
  const AvailableScreen({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AvailableScreenState();
}

class _AvailableScreenState extends State<AvailableScreen>
{

  void _sendAvailability(BuildContext context)
  {
    PhpPost().sendAvailability();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: SafeArea(
        child: Container(
          margin: const EdgeInsets.only(left: 10),
          child: Column(
            children: [
              const SetAvailableSwitch(),
              const AvailableSelectGame(),
              ElevatedButton(onPressed: () {
                    _sendAvailability(context);
                  },
                  child: const Text("OK"))
            ],
          ),
        ),
      ),
    );
  }

}
</code>```

SetAvailableSwitch class :

```<code>class SetAvailableSwitch extends StatefulWidget {

  const SetAvailableSwitch({Key? key}) : super(key: key);

  @override
  _SetAvailableSwitchState createState() => _SetAvailableSwitchState();
}

class _SetAvailableSwitchState extends State<SetAvailableSwitch> {

  bool _isSwitched = false;

  void _changeSwitch(bool value)
  {
    setState(() {
      if(_isSwitched) {
        _isSwitched = false;
      }

      else{
        _isSwitched = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(
          Languages.of(context)!.available,
          style: const TextStyle(),
        ),
        Switch(value: _isSwitched, onChanged: (value)
        {
          _changeSwitch(value);
        })
      ],
    );
  }
}
</code>```

I want to retrieve the boolean in the function void _sendAvailability(BuildContext context) in AvailableScreen class

答:
An option would be to add a callback method to _AvailableScreenState:

```<code>class _AvailableScreenState extends State<AvailableScreen> {
  bool _isSwitched = false;

  void setIsSwitched(switched) {
    setState(() {
      _isSwitched = switched;
    });
    print(_isSwitched);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Container(
          margin: const EdgeInsets.only(left: 10),
          child: Column(
            children: [
              SetAvailableSwitch(setIsSwitched),

</code>```

Which you can call from SetAvailableSwitch:

```<code>class SetAvailableSwitch extends StatefulWidget {
  final void Function(bool) setSwitched;

  const SetAvailableSwitch(this.setSwitched, {Key key}) : super(key: key);

  @override
  _SetAvailableSwitchState createState() => _SetAvailableSwitchState();
}

class _SetAvailableSwitchState extends State<SetAvailableSwitch> {
  bool _isSwitched = false;

  void _changeSwitch(bool value) {
    setState(() {
      if (_isSwitched) {
        _isSwitched = false;
      } else {
        _isSwitched = true;
      }
    });
    widget.setSwitched(_isSwitched);
  }
</code>```

Body:
I want pass the boolean _isSwitched from SetAvailableSwitch class to AvailableScreen class

But actually I can't retrieve the boolean in AvailableScreen class. And as you can see SetAvailableSwitch class is in the Widget build of AvailableScreen class so I don't know how to do that.

AvailableScreen class :

class AvailableScreen extends StatefulWidget
{
  const AvailableScreen({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AvailableScreenState();
}

class _AvailableScreenState extends State<AvailableScreen>
{

  void _sendAvailability(BuildContext context)
  {
    PhpPost().sendAvailability();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: SafeArea(
        child: Container(
          margin: const EdgeInsets.only(left: 10),
          child: Column(
            children: [
              const SetAvailableSwitch(),
              const AvailableSelectGame(),
              ElevatedButton(onPressed: () {
                    _sendAvailability(context);
                  },
                  child: const Text("OK"))
            ],
          ),
        ),
      ),
    );
  }

}

SetAvailableSwitch class :

class SetAvailableSwitch extends StatefulWidget {

  const SetAvailableSwitch({Key? key}) : super(key: key);

  @override
  _SetAvailableSwitchState createState() => _SetAvailableSwitchState();
}

class _SetAvailableSwitchState extends State<SetAvailableSwitch> {

  bool _isSwitched = false;

  void _changeSwitch(bool value)
  {
    setState(() {
      if(_isSwitched) {
        _isSwitched = false;
      }

      else{
        _isSwitched = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(
          Languages.of(context)!.available,
          style: const TextStyle(),
        ),
        Switch(value: _isSwitched, onChanged: (value)
        {
          _changeSwitch(value);
        })
      ],
    );
  }
}

I want to retrieve the boolean in the function void _sendAvailability(BuildContext context) in AvailableScreen class

Body:
An option would be to add a callback method to _AvailableScreenState:

class _AvailableScreenState extends State<AvailableScreen> {
  bool _isSwitched = false;

  void setIsSwitched(switched) {
    setState(() {
      _isSwitched = switched;
    });
    print(_isSwitched);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Container(
          margin: const EdgeInsets.only(left: 10),
          child: Column(
            children: [
              SetAvailableSwitch(setIsSwitched),

Which you can call from SetAvailableSwitch:

class SetAvailableSwitch extends StatefulWidget {
  final void Function(bool) setSwitched;

  const SetAvailableSwitch(this.setSwitched, {Key key}) : super(key: key);

  @override
  _SetAvailableSwitchState createState() => _SetAvailableSwitchState();
}

class _SetAvailableSwitchState extends State<SetAvailableSwitch> {
  bool _isSwitched = false;

  void _changeSwitch(bool value) {
    setState(() {
      if (_isSwitched) {
        _isSwitched = false;
      } else {
        _isSwitched = true;
      }
    });
    widget.setSwitched(_isSwitched);
  }


问:
Composite Foreign Key Question
I am trying to figure out if it is possible to create a foreign key in this way.

First there are two parent tables in this scenario.

Table 1 has a PK int and another int column. When combined the two are unique.

Table 2 has a PK int and another int column. When combined the two are unique.

The paired value between the two ints is how we currently select the child records for either table.

Table 3 has a value for the PK and other int column from one of the first two tables. It is reliably selectable because the two fields when both used in a search are unique to one of the above tables.

So I am looking to create a FK or possibly two FK for this scenario. I would like to be able to do cascading deletes from either of the first tables into the third table, and would also like to use this for the entity relationships in Entity Framework.

Please let me know if this is not making sense. I have read it several times, and it is about as clear as I can get it.

Thanks

答:
If I understand you correctly, you have 3 tables structured as follows:

```<code>TABLE_A:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL, NOT IN TABLE_B.OTHER_FIELD

TABLE_B:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL, NOT IN TABLE_A.OTHER_FIELD

TABLE_C:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL IN (TABLE_A.OTHER_FIELD OR TABLE_B.OTHER_FIELD
</code>```

What you are trying to do is define TABLE_C such that you could cascade updates and deletes between the tables. Because of how TABLE_A.OTHER_FIELD and TABLE_B.OTHER_FIELD are defined, you will guarantee that there is no overlap between them. The problem is figuring out which table has the reference to TABLE_C.

What you can do with this definition is cascade from TABLE_A or TABLE_B to TABLE_C since the relationship is quite clear in that direction. However, to cascade from TABLE_C up is more complicated, since you don't know which table to cascade to. Either define two fields in TABLE_C one to reference each of the other tables, and then you can define the relationship between all three tables, knowing that for any given record there will only be one or two tables involved, never all three. Alternatively, you can use code to figure out which table to relate this particular row to and cascade accordingly.

ContentLicense: CC BY-SA 2.5

Title: Composite Foreign Key Question

Body:
If I understand you correctly, you have 3 tables structured as follows:

TABLE_A:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL, NOT IN TABLE_B.OTHER_FIELD

TABLE_B:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL, NOT IN TABLE_A.OTHER_FIELD

TABLE_C:
    PK_FIELD int NOT NULL
    OTHER_FIELD int NOT NULL IN (TABLE_A.OTHER_FIELD OR TABLE_B.OTHER_FIELD

What you are trying to do is define TABLE_C such that you could cascade updates and deletes between the tables. Because of how TABLE_A.OTHER_FIELD and TABLE_B.OTHER_FIELD are defined, you will guarantee that there is no overlap between them. The problem is figuring out which table has the reference to TABLE_C.

What you can do with this definition is cascade from TABLE_A or TABLE_B to TABLE_C since the relationship is quite clear in that direction. However, to cascade from TABLE_C up is more complicated, since you don't know which table to cascade to. Either define two fields in TABLE_C one to reference each of the other tables, and then you can define the relationship between all three tables, knowing that for any given record there will only be one or two tables involved, never all three. Alternatively, you can use code to figure out which table to relate this particular row to and cascade accordingly.

OwnerDisplayName: Elie


答:
From Other model instance methods[Django-doc]

Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object

In your Person model use str()[Django-doc] as

```<code>class Person(models.Model):
    name = models.charField(max_length=100)
    .....

    def __str__(self):
        return self.name
</code>```

Title: In django-forms, how can I make the values of 'name' column of foreign database visible in the selection choices

Body:
From Other model instance methods[Django-doc]

Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object

In your Person model use str()[Django-doc] as

class Person(models.Model):
    name = models.charField(max_length=100)
    .....

    def __str__(self):
        return self.name


问:
How to force yarn to override yarn.lock version and install latest?
I would like to keep all other package versions in tact, but upgrade one single package to the most recent version. How can I do that using yarn?

I know I can delete yarn.lock, and then run yarn install, but I think that will upgrade every package, which I don't want. I just want the most recent version of node-sass, and for that to override the version I have in yarn.lock.

How can this be done?

答:
According to Yarn documentation:

```<code>yarn up [package]
yarn up [package]@[version]
yarn up [package]@[tag]
</code>```

So, to upgrade node-sass, you should run:

```<code>yarn up node-sass
</code>```

Body:
According to Yarn documentation:

yarn up [package]
yarn up [package]@[version]
yarn up [package]@[tag]

So, to upgrade node-sass, you should run:

yarn up node-sass


问:
Font Awesome 5 on pseudo elements shows square instead of icon
I am trying to change the content of a span with a Font Awesome icon directly from the CSS page but can't seem to make it work properly.

1) I have imported FA from the documentation and in the

```<code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css" integrity="sha384-5SOiIsAziJl6AWe0HWRKTXlfcSHKmYV4RBF18PPJ173Kzn7jzMyFuTtk8JA7QQG1" crossorigin="anonymous">
</code>```

2) My html looks like this :

```<code><span class='myClass'>Movies</span>
</code>```

3) Let's now say I would like to change the content of the span with an icon directly from the CSS Page.

My css currently looks like this but it isn't working, it gives me a square instead of the icon.

.myClass {
  font-size:25px;
}

.myClass::after {
  font-family: 'Font Awesome 5 Free';
  content: '\f008';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css">
<span class='myClass'></span></code>```

Funny thing is that it looks like it is working with some icons. If I test with content: '\f007'; it works. Any idea why?

(And if you wonder why I want to change the icon directly in the CSS, it is because I am using media queries so I can't add it directly in the HTML page)

答:
```<code>list-style-image: url("../../media/examples/rocket.svg");
</code>```

source: https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image

Body:
I am trying to change the content of a span with a Font Awesome icon directly from the CSS page but can't seem to make it work properly.

1) I have imported FA from the documentation and in the

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css" integrity="sha384-5SOiIsAziJl6AWe0HWRKTXlfcSHKmYV4RBF18PPJ173Kzn7jzMyFuTtk8JA7QQG1" crossorigin="anonymous">

2) My html looks like this :

Movies

3) Let's now say I would like to change the content of the span with an icon directly from the CSS Page.

My css currently looks like this but it isn't working, it gives me a square instead of the icon.

.myClass {
  font-size:25px;
}

.myClass::after {
  font-family: 'Font Awesome 5 Free';
  content: '\f008';
}

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css">

Funny thing is that it looks like it is working with some icons. If I test with content: '\f007'; it works. Any idea why?

(And if you wonder why I want to change the icon directly in the CSS, it is because I am using media queries so I can't add it directly in the HTML page)

Body:
list-style-image: url("../../media/examples/rocket.svg");

source: https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image


问:
Transpose a tibble
I have this tibble:

```<code>tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
</code>```

I want to transpose it into this tibble:

```<code>tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)
</code>```

Is there a tidyverse simple command to do so?

答:
We can use data.table::transpose

```<code>as_tibble(data.table::transpose(dat, make.names = 'Cor', keep.names = 'Cor'))
 # A tibble: 2 × 3
  Cor   Linear Rank
  <chr> <chr>  <chr>
1 a,b   x1     x2
2 b,c   x3     x4
</code>```

data

```<code>dat <- tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
</code>```

Title: Transpose a tibble

Body:
I have this tibble:

tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)

I want to transpose it into this tibble:

tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)

Is there a tidyverse simple command to do so?

Body:
We can use data.table::transpose

as_tibble(data.table::transpose(dat, make.names = 'Cor', keep.names = 'Cor'))
 # A tibble: 2 × 3
  Cor   Linear Rank
  <chr> <chr>  <chr>
1 a,b   x1     x2
2 b,c   x3     x4

data

dat <- tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)


问:
Creating a generic base entity which can be extended for each client
I'm using Eclipselink and I'm trying figure out the best way to create a base class for my entity.

For example, I have a User entity and I would like to provide an extended User class for some clients, but I would like to not have to rewrite my generic queries.

So I would have a User entity and a ClientSpecificUser entity, but be able to pull up ClientSpecificUser by using the query "select e from User e".

Has anyone done something like?  What worked best?

答:
Java 5 Generics could be a good fit for this issue, to institute a generic DAO layer.  Here are 2 examples:

http://community.jboss.org/wiki/GenericDataAccessObjects

http://nileshk.com/2006/05/09/hibernate-dao-using-java-generics.html


问:
Why am I getting a lifetime mismatch?
The following function compiles without issues:

async fn filter_con<T, O, F>(arr: Vec<T>, predicate: F) -> Vec<T>
where
    O: Future<Output = bool>,
    F: for Fn(&T) -> O,
{
    join_all(arr.into_iter().map(|it| async {
        if predicate(&it).await {
            Some(it)
        } else {
            None
        }
    }))
    .await
    .into_iter()
    .filter_map(|p| p)
    .collect::<Vec<_>>()
}
```
<p>But I can't find a way to call it properly:</p>
<pre class="lang-rust prettyprint-override"><code>let items_filtered = filter_con(items, filter).await;
</code>```

Error:

error[E0308]: mismatched types
   --> src/lifecycle/querier.rs:101:30
    |
101 |         let items_filtered = filter_con(items_response, filter).await;
    |                              ^^^^^^^^^^ lifetime mismatch
    |
    = note: expected associated type `<for<'_> fn(&PairInfo) -> impl futures::Future<Output = bool> {lifecycle::querier::filter} as FnOnce<(&PairInfo,)>>::Output`
               found associated type `<for<'_> fn(&PairInfo) -> impl futures::Future<Output = bool> {lifecycle::querier::filter} as FnOnce<(&PairInfo,)>>::Output`
    = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
   --> src/lifecycle/querier.rs:246:26
    |
246 |     F: for<'a> Fn(&T) -> O,
    |                          ^
```

Why is this happening?

Full playground here

答:
You have essentially the same problem as in here

To make it easier to understand I'll rewrite/desugar some of your code. Let's start with the predicate:

async fn filter(x: &Test) -> bool{
    x.0 >= 50
}
```
<p>Is functionally equivalent to:</p>
<pre class="lang-rust prettyprint-override"><code>fn filter(x: &Test) -> impl Future<Output=bool> + '_{
    async {
        x.0 >= 50
    }
}
</code>```

Now it should be obvious that the lifetime of the returned Future is not 'static, but actually it depends on the lifetime of the parameter x: &Test.

This should make the error more understandable - your predicate is returning some future with some lifetime, which is not mentioned anywhere in the generic type definition - you can see that you don't mention it when you define neither O, nor F:

where
    O: Future<Output = bool>,
    F: for Fn(&T) -> O,
```
<p>The problem is that, currently the language does not provide any means to say that <code>O</code>'s lifetime depends on <code>F</code>'s lifetime. The only easy solution I know is to use the escape hatch - <code>box</code> the future, which will allow you to use the same lifetime in <code>F</code> and <code>O</code>. the downside is that, <code>F</code> will be heap allocated:</p>
<pre class="lang-rust prettyprint-override"><code>use futures::future::{join_all, Future};
use futures::future::BoxFuture;
use futures::FutureExt;

#[derive(Debug)]
struct Test(usize);

#[tokio::main]
async fn main() {
    let items = vec![Test(10), Test(100), Test(1000)];
    let items_filtered = filter_con(items, filter).await;

    println!("{:?}", items_filtered); // should print [100, 1000]
}

fn filter(x: &Test) -> BoxFuture<'_, bool>{
    async {
        x.0 >= 50
    }.boxed()
}

async fn filter_con<T, F>(arr: Vec<T>, predicate: F) -> Vec<T>
where
    F: for<'a> Fn(&'a T) -> BoxFuture<'a, bool>,
{
    join_all(arr.into_iter().map(|it| async{
        if predicate(&it).await {
            Some(it)
        } else {
            None
        }
    }))
    .await
    .into_iter()
    .filter_map(|p| p)
    .collect::<Vec<_>>()
}
</code>```

Here is a link to the Rust Plauground

Title: Why am I getting a lifetime mismatch?

Body:
The following function compiles without issues:

async fn filter_con<T, O, F>(arr: Vec<T>, predicate: F) -> Vec<T>
where
    O: Future<Output = bool>,
    F: for Fn(&T) -> O,
{
    join_all(arr.into_iter().map(|it| async {
        if predicate(&it).await {
            Some(it)
        } else {
            None
        }
    }))
    .await
    .into_iter()
    .filter_map(|p| p)
    .collect::<Vec<_>>()
}

But I can't find a way to call it properly:

let items_filtered = filter_con(items, filter).await;

Error:

error[E0308]: mismatched types
   --> src/lifecycle/querier.rs:101:30
    |
101 |         let items_filtered = filter_con(items_response, filter).await;
    |                              ^^^^^^^^^^ lifetime mismatch
    |
    = note: expected associated type `<for<'_> fn(&PairInfo) -> impl futures::Future<Output = bool> {lifecycle::querier::filter} as FnOnce<(&PairInfo,)>>::Output`
               found associated type `<for<'_> fn(&PairInfo) -> impl futures::Future<Output = bool> {lifecycle::querier::filter} as FnOnce<(&PairInfo,)>>::Output`
    = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
   --> src/lifecycle/querier.rs:246:26
    |
246 |     F: for<'a> Fn(&T) -> O,
    |                          ^

Why is this happening?

Full playground here

Body:
You have essentially the same problem as in here

To make it easier to understand I'll rewrite/desugar some of your code. Let's start with the predicate:

async fn filter(x: &Test) -> bool{
    x.0 >= 50
}

Is functionally equivalent to:

fn filter(x: &Test) -> impl Future<Output=bool> + '_{
    async {
        x.0 >= 50
    }
}

Now it should be obvious that the lifetime of the returned Future is not 'static, but actually it depends on the lifetime of the parameter x: &Test.

This should make the error more understandable - your predicate is returning some future with some lifetime, which is not mentioned anywhere in the generic type definition - you can see that you don't mention it when you define neither O, nor F:

where
    O: Future<Output = bool>,
    F: for Fn(&T) -> O,

The problem is that, currently the language does not provide any means to say that O's lifetime depends on F's lifetime. The only easy solution I know is to use the escape hatch - box the future, which will allow you to use the same lifetime in F and O. the downside is that, F will be heap allocated:

use futures::future::{join_all, Future};
use futures::future::BoxFuture;
use futures::FutureExt;

#[derive(Debug)]
struct Test(usize);

#[tokio::main]
async fn main() {
    let items = vec![Test(10), Test(100), Test(1000)];
    let items_filtered = filter_con(items, filter).await;

    println!("{:?}", items_filtered); // should print [100, 1000]
}

fn filter(x: &Test) -> BoxFuture<'_, bool>{
    async {
        x.0 >= 50
    }.boxed()
}

async fn filter_con<T, F>(arr: Vec<T>, predicate: F) -> Vec<T>
where
    F: for<'a> Fn(&'a T) -> BoxFuture<'a, bool>,
{
    join_all(arr.into_iter().map(|it| async{
        if predicate(&it).await {
            Some(it)
        } else {
            None
        }
    }))
    .await
    .into_iter()
    .filter_map(|p| p)
    .collect::<Vec<_>>()
}

Here is a link to the Rust Plauground


问:
CSS Div overlaps text
I'm releasing a new feature on my website and I want to mark the new a-tag in the navbar with a "NEW" sign top right of the a-tag (little overlapping). But I don't know how to make this overlapping happen and that my span with "NEW" (the text) is shown in full-width. Difficult to describe for me, current status is in the picture. I tried z-index, didn't work.
Here is my code.

navbar html and css:

```<code><li class="nav-item p-1">
      <a class="nav-link" routerLink="overview/cases" routerLinkActive="active-link" (click)="collapsed=true">Cases<span class="new-feature">NEW</span></a>
    </li>

    .new-feature{
      width: 50px;
      height: 20px;
     background: linear-gradient(135deg, #9932cc, #fa490a);
      color: #fff;
      font-size: 15px;
      border-radius: 15px;
      text-align: center;
    }
</code>```

It currently looks like this:

答:
Give position:absolute to .new-feature and position:relative to its parent class. You can play with values to fit to your need.

*{
    margin:0px;
    padding: 0px;
}
.nav-item{
    list-style: none;
    padding: 10px;
}

.new-feature-wrapper{
    position: relative;
}
.new-feature{
    position: absolute;
    width: 30px;
    height: 10px;
   background: linear-gradient(135deg, #9932cc, #fa490a);
    color: #fff;
    font-size: 12px;
    border-radius: 15px;
    text-align: center;
    padding: 5px;
    top: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="nav-item p-1 new-feature-wrapper">
            Cases<span class="new-feature">NEW</span>
        </li></code>```

Title: CSS Div overlaps text

Body:
I'm releasing a new feature on my website and I want to mark the new a-tag in the navbar with a "NEW" sign top right of the a-tag (little overlapping). But I don't know how to make this overlapping happen and that my span with "NEW" (the text) is shown in full-width. Difficult to describe for me, current status is in the picture. I tried z-index, didn't work.
Here is my code.

navbar html and css:

      CasesNEW

    .new-feature{
      width: 50px;
      height: 20px;
     background: linear-gradient(135deg, #9932cc, #fa490a);
      color: #fff;
      font-size: 15px;
      border-radius: 15px;
      text-align: center;
    }

It currently looks like this:

Body:
Give position:absolute to .new-feature and position:relative to its parent class. You can play with values to fit to your need.

*{
    margin:0px;
    padding: 0px;
}
.nav-item{
    list-style: none;
    padding: 10px;
}

.new-feature-wrapper{
    position: relative;
}
.new-feature{
    position: absolute;
    width: 30px;
    height: 10px;
   background: linear-gradient(135deg, #9932cc, #fa490a);
    color: #fff;
    font-size: 12px;
    border-radius: 15px;
    text-align: center;
    padding: 5px;
    top: 2px;
}

<li class="nav-item p-1 new-feature-wrapper">
            <a class="nav-link" routerLink="overview/cases" routerLinkActive="active-link" (click)="collapsed=true">Cases<span class="new-feature">NEW</span></a>
        </li>


问:
How can i restrict unauthenticated access to Firebase Firestore while permitting new users to add account data?
I am using firebase authentication on my reactJS application.
When a user signs up, an entry is added into firestore to store some account details at user/(UID).

I need to create firestore rules that willL

Prevent unauthenticated users from reading and writing to firestore

Only allow users to read their own data in firestore Users/(users UID)

Allow newly registered users to write to firestore so data can be added for their account.

I have tried the following:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
        match /users/{userId}/{document=**} {
        allow read, write: if request.auth != null && request.auth.uid == userId;
      }
      allow read;
      allow write: if request.auth != null;
    }
  }
}

</code>```

But i am receiving an email each day from Firebase saying my rules are insecure and anyone can write to my database.
How can i fix this?

答:
You have a recursive wildcard (/{document=**}) with the rule allow write: if request.auth != null; which allows any authenticated user to write in any collection/document of the database. Based on the given constraint, try refactoring your rules to:

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{sub=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}
</code>```

Body:
I am using firebase authentication on my reactJS application.
When a user signs up, an entry is added into firestore to store some account details at user/(UID).

I need to create firestore rules that willL

Prevent unauthenticated users from reading and writing to firestore

Only allow users to read their own data in firestore Users/(users UID)

Allow newly registered users to write to firestore so data can be added for their account.

I have tried the following:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
        match /users/{userId}/{document=**} {
        allow read, write: if request.auth != null && request.auth.uid == userId;
      }
      allow read;
      allow write: if request.auth != null;
    }
  }
}

But i am receiving an email each day from Firebase saying my rules are insecure and anyone can write to my database.
How can i fix this?

Body:
You have a recursive wildcard (/{document=**}) with the rule allow write: if request.auth != null; which allows any authenticated user to write in any collection/document of the database. Based on the given constraint, try refactoring your rules to:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{sub=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}