问:
Update values dynamically in MongoDB
I'm working on an inventory management app, and I need to update inventories according to a value provided by the user. Let's say we have 5 of one item, the user adds 3 on the front-end form, the updated value should be 8.
I've been unable to make mongo update the number.

```<code>router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
const {id} = req.params;
const qty = parseInt(req.body.cantidad)
if(qty>0){
    const item = await Inv.findById(id)
    const update = parseInt(req.body.cantidad) + item.cantidad
    const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true})
    res.redirect(`/inv/show/${item._id}`)
} else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
}}));
</code>```

And here's my model:

```<code>const InvSchema = new Schema({
nombre: {
    type: String,
    required: true,
    unique: true
},
cantidad: Number
});
</code>```

答:
You didn't change your update statement right. You shouldn't remove the first argument. As I said {new: true} should be the third input.
Anyway I think there is a better solution for what you want to do. As you already find the record with findById, you can use mongo/monoose save command instead of another findOneAndUpdate:

router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
  const {id} = req.params;
  const qty = parseInt(req.body.cantidad)
  if(qty>0){
    const item = await Inv.findById(id)
    item.cantidad = parseInt(req.body.cantidad) + item.cantidad // Change this line to change item's property directly
    await item.save() // Save the item in database
    //const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true}) // Remove this line
    res.redirect(`/inv/show/${item._id}`)
  } else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
  }
}));
```

I think this is a cleaner approach.

Title: Update values dynamically in MongoDB

Body:
I'm working on an inventory management app, and I need to update inventories according to a value provided by the user. Let's say we have 5 of one item, the user adds 3 on the front-end form, the updated value should be 8.
I've been unable to make mongo update the number.

router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
const {id} = req.params;
const qty = parseInt(req.body.cantidad)
if(qty>0){
    const item = await Inv.findById(id)
    const update = parseInt(req.body.cantidad) + item.cantidad
    const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true})
    res.redirect(`/inv/show/${item._id}`)
} else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
}}));

And here's my model:

const InvSchema = new Schema({
nombre: {
    type: String,
    required: true,
    unique: true
},
cantidad: Number
});

Body:
You didn't change your update statement right. You shouldn't remove the first argument. As I said {new: true} should be the third input.
Anyway I think there is a better solution for what you want to do. As you already find the record with findById, you can use mongo/monoose save command instead of another findOneAndUpdate:

router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
  const {id} = req.params;
  const qty = parseInt(req.body.cantidad)
  if(qty>0){
    const item = await Inv.findById(id)
    item.cantidad = parseInt(req.body.cantidad) + item.cantidad // Change this line to change item's property directly
    await item.save() // Save the item in database
    //const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true}) // Remove this line
    res.redirect(`/inv/show/${item._id}`)
  } else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
  }
}));

I think this is a cleaner approach.


来源: stackexchange

问:
Anonymous function implementation in flutter
So, I am learning about anonymous functions in dart which I know helps to reduce and simplify the code when passing a function as an argument to another function. Now, what I want to know is how exactly is this used in building an application using flutter. I am here seeking some practical implementation in actual flutter applications.</p>

答:
Let's have a look at this example:

```<code>final updatedUser = repository.updateUser(
      onError: () {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text('User could not be updated'),
        ));
      },
      onSuccess: () {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('User updated'),
          ),
        );
      },
    );
</code>```

repository.dart

```<code>Future<User> updateUser({
    void Function()? onSuccess,
    void Function()? onError,
  }) async {
    final response = await api.updateUser();
    if (response.statusCode == 200) {
      onSuccess?.call();
    }
    if (response.statusCode! < 200 || response.statusCode! > 300) {
      onError?.call();
    }
    return response.data!
  }
</code>```

The repository shouldn't know about anything about a BuildContext so we can't show a snackbar right in it.
To show them anyway we can do this in callbacks, using the context of the calling widget.

ContentLicense: CC BY-SA 4.0

Body:
Let's have a look at this example:

final updatedUser = repository.updateUser(
      onError: () {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text('User could not be updated'),
        ));
      },
      onSuccess: () {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('User updated'),
          ),
        );
      },
    );

repository.dart

Future<User> updateUser({
    void Function()? onSuccess,
    void Function()? onError,
  }) async {
    final response = await api.updateUser();
    if (response.statusCode == 200) {
      onSuccess?.call();
    }
    if (response.statusCode! < 200 || response.statusCode! > 300) {
      onError?.call();
    }
    return response.data!
  }

The repository shouldn't know about anything about a BuildContext so we can't show a snackbar right in it.
To show them anyway we can do this in callbacks, using the context of the calling widget.


问:
Javascript Multiplying Within an Array
I have an array with multiple arrays inside.  I would like to multiply the contents of each array.

Here is my code--currently not getting anything in console.
The desired output is 3 numbers-- the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}```

答:
You can try this, it is easier using map and reduce functions. arr.map(array => array.reduce(arrayMult, 1)) is the multiplication of each inner array, like [ 6, 12, 504 ], and the last reduce is to multiply these values.

```<code>var arr = [[1, 2, 3],[3, 4],[7, 8, 9]];
const arrayMult = (prev, curr) => prev * curr;
const total = arr.map(array => array.reduce(arrayMult, 1)).reduce(arrayMult, 1);
</code>```

Title: Javascript Multiplying Within an Array

Body:
You can try this, it is easier using map and reduce functions. arr.map(array => array.reduce(arrayMult, 1)) is the multiplication of each inner array, like [ 6, 12, 504 ], and the last reduce is to multiply these values.

var arr = [[1, 2, 3],[3, 4],[7, 8, 9]];
const arrayMult = (prev, curr) => prev * curr;
const total = arr.map(array => array.reduce(arrayMult, 1)).reduce(arrayMult, 1);


问:
In GCD, is there a way to tell if the current queue is concurrent or not?
In GCD, is there a way to tell if the current queue is concurrent or not?
I'm current attempting to perform a delayed save on some managed object contexts but I need to  make sure that the queue the code is currently executed on is thread-safe (in a synchronous queue).</p>

答:
Yes, assuming you're doing the work in an NSOperation subclass:

```<code>[myOperation isConcurrent] //or self, if you're actually in the NSOperation
</code>```

If you need to ensure some operations are always executed synchronously, you can create a specific operation queue and set its maximum concurrent operations to 1.

```<code>NSOperationQueue * synchronousQueue = [[NSOperationQueue alloc] init];
[synchronousQueue setMaxConcurrentOperationCount:1];
</code>```

GCD takes some planning ahead. The only other way I can think of is to observe the value isExecuting (or similar) on your NSOperation objects. Check out this reference on that. This solution would be more involved, so I hope the other one works for you.

ContentLicense: CC BY-SA 3.0

Body:
Yes, assuming you're doing the work in an NSOperation subclass:

[myOperation isConcurrent] //or self, if you're actually in the NSOperation

If you need to ensure some operations are always executed synchronously, you can create a specific operation queue and set its maximum concurrent operations to 1.

NSOperationQueue * synchronousQueue = [[NSOperationQueue alloc] init];
[synchronousQueue setMaxConcurrentOperationCount:1];

GCD takes some planning ahead. The only other way I can think of is to observe the value isExecuting (or similar) on your NSOperation objects. Check out this reference on that. This solution would be more involved, so I hope the other one works for you.


答:
Nothing wrong with good old iterating; your existing approach only had one bug, on the inner loop you were still checking the length of the top-level array instead of the inner array; j should range from 0 to arr[i].length, not arr.length.

An alternative approach uses map and reduce; comments below explain how it works:

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]

console.log(
  arr.map(a => {  // <-- calls a function on each element of arr,
                  // leaving the results in an array
    return a.reduce( // <-- reducer is like map, calling a function
                     // on each element of a,  but collects its results
                     // in a "collector" variable passed to each step
      (val, sum) => {return val * sum}, // <-- multiply this value with
                                        // the ones so far
      1 // <-- initial value for the collector
    )
  })
)```

Title: Javascript Multiplying Within an Array

Body:
I have an array with multiple arrays inside.  I would like to multiply the contents of each array.

Here is my code--currently not getting anything in console.
The desired output is 3 numbers-- the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}


问:
I want to ask, how can I disconnect tkinter's .bind
I've been experimenting recently
Found that I can drag, move the button or the configuration inside

But I keep trying to let go and never follow
But there's no way, stop
.bind. I have used if and button switches and still can't do it, I hope someone can help me think of a way

What I want is to call out the picture, and it can be dragged to the specified position to place it, moved over and pressed to move, and it will move with it.

The newcomer posts, if the post offends the engineers, I will apologize to everyone first.

```<code>import tkinter as tk
new_x =50
new_y =50
mgs=False
def click():
    global mgs
    if mgs ==False:
        mgs =True

        root.after(1000,move)
    else:
        mgs =False

# def B1Motion():
#     root.bind("<B1-Motion>",move)
def aa(event):
    global new_x

    global new_y
    new_x = event.x
    new_y = event.y
    # print(new_y)
    # print(new_x)
    print(new_x,new_y,"\r",end="",flush=True)

def move(event):
    # global new_x

    # global new_y
    # new_x = event.x
    # new_y = event.y
    # super event.x
    # super event.y
    new_x = event.x
    new_y = event.y
    c.place(x=new_x, y=new_y)
    # self.after(1000, increment_textOne)
    # b.place(x=new_x, y=new_y)
    # print(new_y,"\r",end="",flush=True)
# def even(event):
#     while True:
#         root.bind("<B1-Motion>",move)

# --- main ---
# command=move
root = tk.Tk()
a = tk.Button(root, text='it')
b = tk.Button(root, text='Move it',command=click)
root.bind("<B1-Motion>",aa)
# root.bind("<B1-Motion>",move)
# while break_program == True:
#     new_x = event.x
#     new_y = event.y
#     b.place(x=new
#     _x, y=new_y)
#     print(event.x)
#     time.sleep(5)
c=tk.Canvas(root,bg="red",height=40, width=40)
# root.bind("<B1-Motion>",move)
# c.bind("<Enter>",even)
root.bind("<B1-Motion>",move)
# root.bind("<B1-Motion><FocusIn>",move)
# if c.event.type =="Enter":
#     root.bind("<B1-Motion>",move)
# root.after(1000,click)
b.place(x=100,y=100)
a.place(x=20,y=20)

print(new_x)
root.mainloop()

</code>```

答:
Tkinter provides the unbind(seq,callback) for this.

After binding an event you get a reference to that binding and with this reference you can unbind your callback from the event, like in the example below.

```<code>import tkinter as tk

def OnEnter(event):
    global motion_binding
    motion_binding = canvas.bind('<B1-Motion>', OnMotion)
def OnLeave(event):
    canvas.unbind('<B1-Motion>',motion_binding)
    canvas.unbind('<Enter>',enter_binding)
    canvas.unbind('<Leave>',leave_binding)
def OnMotion(event):
    x,y = event.x,event.y
    canvas.coords(rectangle, x,y,x+100,y+100)

root = tk.Tk()
canvas = tk.Canvas(root,bg='blue')
rectangle = canvas.create_rectangle(0,0,100,100,fill='red')
enter_binding = canvas.bind('<Enter>', OnEnter)
leave_binding = canvas.bind('<Leave>',OnLeave)
print(enter_binding)
canvas.pack()
</code>```

Body:
I've been experimenting recently
Found that I can drag, move the button or the configuration inside

But I keep trying to let go and never follow
But there's no way, stop
.bind. I have used if and button switches and still can't do it, I hope someone can help me think of a way

What I want is to call out the picture, and it can be dragged to the specified position to place it, moved over and pressed to move, and it will move with it.

The newcomer posts, if the post offends the engineers, I will apologize to everyone first.

import tkinter as tk
new_x =50
new_y =50
mgs=False
def click():
    global mgs
    if mgs ==False:
        mgs =True

        root.after(1000,move)
    else:
        mgs =False

# def B1Motion():
#     root.bind("<B1-Motion>",move)
def aa(event):
    global new_x

    global new_y
    new_x = event.x
    new_y = event.y
    # print(new_y)
    # print(new_x)
    print(new_x,new_y,"\r",end="",flush=True)

def move(event):
    # global new_x

    # global new_y
    # new_x = event.x
    # new_y = event.y
    # super event.x
    # super event.y
    new_x = event.x
    new_y = event.y
    c.place(x=new_x, y=new_y)
    # self.after(1000, increment_textOne)
    # b.place(x=new_x, y=new_y)
    # print(new_y,"\r",end="",flush=True)
# def even(event):
#     while True:
#         root.bind("<B1-Motion>",move)

# --- main ---
# command=move
root = tk.Tk()
a = tk.Button(root, text='it')
b = tk.Button(root, text='Move it',command=click)
root.bind("<B1-Motion>",aa)
# root.bind("<B1-Motion>",move)
# while break_program == True:
#     new_x = event.x
#     new_y = event.y
#     b.place(x=new
#     _x, y=new_y)
#     print(event.x)
#     time.sleep(5)
c=tk.Canvas(root,bg="red",height=40, width=40)
# root.bind("<B1-Motion>",move)
# c.bind("<Enter>",even)
root.bind("<B1-Motion>",move)
# root.bind("<B1-Motion><FocusIn>",move)
# if c.event.type =="Enter":
#     root.bind("<B1-Motion>",move)
# root.after(1000,click)
b.place(x=100,y=100)
a.place(x=20,y=20)

print(new_x)
root.mainloop()

Body:
Tkinter provides the unbind(seq,callback) for this.

After binding an event you get a reference to that binding and with this reference you can unbind your callback from the event, like in the example below.

import tkinter as tk

def OnEnter(event):
    global motion_binding
    motion_binding = canvas.bind('<B1-Motion>', OnMotion)
def OnLeave(event):
    canvas.unbind('<B1-Motion>',motion_binding)
    canvas.unbind('<Enter>',enter_binding)
    canvas.unbind('<Leave>',leave_binding)
def OnMotion(event):
    x,y = event.x,event.y
    canvas.coords(rectangle, x,y,x+100,y+100)

root = tk.Tk()
canvas = tk.Canvas(root,bg='blue')
rectangle = canvas.create_rectangle(0,0,100,100,fill='red')
enter_binding = canvas.bind('<Enter>', OnEnter)
leave_binding = canvas.bind('<Leave>',OnLeave)
print(enter_binding)
canvas.pack()


问:
Making a code to disable a css of a tag and enable the css on an other tag
I'm making a website and I want to make a guide with pulse animation. There are 3 tags that I want to use. For example three  links, I want:

first link starts pulsing and when I clicked on it its css be disabled and

the second link starts pulsing, and

a third one like this

I think it may be possible with javascript but I dont know how.

For example:

   #live-heart{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }
      #live-heart2{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }
      #live-heart3{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>first one
<p>
When a user clicked on "first one" its css shoul be disabled and a second one that I linked in paragraph be enabled second one
and when a user clicked on second one, its css be disabled and the third one be activeted
example text: bla bla bla bla
</p>
third one</code>```

答:
basically all you need is to having a state holding the active pulsing link index. and by clicking it, increase the index by one.

something like that:

const [isPulsingIndex, setIsPulsingIndex] = useState(0);

<Link className={isPulsing.index === 0 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(1)}>
    Link 1
</Link>
<Link className={isPulsing.index === 1 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(2)}>
    Link 1
</Link>
<Link className={isPulsing.index === 2 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(3)}>
    Link 1
</Link>```

quick example of how adding and removing class from a tag dynamically using state

Body:
I'm making a website and I want to make a guide with pulse animation. There are 3 tags that I want to use. For example three  links, I want:

first link starts pulsing and when I clicked on it its css be disabled and

the second link starts pulsing, and

a third one like this

I think it may be possible with javascript but I dont know how.

For example:

   #live-heart{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }
      #live-heart2{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }
      #live-heart3{
    animation:pulse 1500ms infinite ;
    border-radius:20px;
   }
   @keyframes pulse{
     0% {
       box-shadow:#f33 0 0 0 0;
     }
     75%{
       box-shadow:rgba(65, 30, 30, 0.8) 0 0 0 16px
     }
   }

first one

When a user clicked on "first one" its css shoul be disabled and a second one that I linked in paragraph be enabled second one
and when a user clicked on second one, its css be disabled and the third one be activeted
example text: bla bla bla bla

third one

Body:
basically all you need is to having a state holding the active pulsing link index. and by clicking it, increase the index by one.

something like that:

const [isPulsingIndex, setIsPulsingIndex] = useState(0);

<Link className={isPulsing.index === 0 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(1)}>
    Link 1
</Link>
<Link className={isPulsing.index === 1 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(2)}>
    Link 1
</Link>
<Link className={isPulsing.index === 2 ? 'pulsing' : ''}
  onClick={() => setIsPulsingIndex(3)}>
    Link 1
</Link>

quick example of how adding and removing class from a tag dynamically using state


问:
Remove duplicates from list of lists by column value
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

```<code>[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]
</code>```

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

答:
I would probably convert to Pandas DataFrame and then use drop_duplicates</p>
```<code>import pandas as pd
data = [
{'id': '23', 'type': 'car', 'price': '445'},
{'id': '23', 'type': 'car', 'price': '78'},
{'id': '23', 'type': 'car', 'price': '34'},
{'id': '125', 'type': 'truck', 'price': '998'},
{'id': '125', 'type': 'truck', 'price': '722'},
{'id': '125', 'type': 'truck', 'price': '100'},
{'id': '87', 'type': 'bike', 'price': '50'},
]
df = pd.DataFrame(data)
df.drop_duplicates(subset=['id'], inplace=True)
print(df.to_dict('records'))

# Output
# [{'id': '23', 'type': 'car', 'price': '445'},
# {'id': '125', 'type': 'truck', 'price': '998'},
# {'id': '87', 'type': 'bike', 'price': '50'}]
</code>```

Body:
I have a list of list that look like this, they have been sorted so that duplicate IDs are arranged with the one I want to keep at the top..

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

What is the simplest way to remove rows that have duplicate IDs but always keep the first one? In this instance the end result would look like this...

[
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

I know I can remove duplicates from lists by converting to set like set(my_list) but in this instance it is duplicates by ID that I want to remove by

Body:
I would probably convert to Pandas DataFrame and then use drop_duplicates

import pandas as pd
data = [
{'id': '23', 'type': 'car', 'price': '445'},
{'id': '23', 'type': 'car', 'price': '78'},
{'id': '23', 'type': 'car', 'price': '34'},
{'id': '125', 'type': 'truck', 'price': '998'},
{'id': '125', 'type': 'truck', 'price': '722'},
{'id': '125', 'type': 'truck', 'price': '100'},
{'id': '87', 'type': 'bike', 'price': '50'},
]
df = pd.DataFrame(data)
df.drop_duplicates(subset=['id'], inplace=True)
print(df.to_dict('records'))

# Output
# [{'id': '23', 'type': 'car', 'price': '445'},
# {'id': '125', 'type': 'truck', 'price': '998'},
# {'id': '87', 'type': 'bike', 'price': '50'}]


问:
Can the acf function properly compute autocorrelation with a binary vector?
Hi supposed I have a vector consisting of 0's and 1's; will the default acf function be able to calculate this correctly?

```<code>set.seed ( 12 )
bin = sample(c(0,1), replace=TRUE, size=5000)
acf (bin )
</code>```

答:
Yes. Your example doesn't work because it is completely random. But we can create a binomial sample with an oscillating probability of 1s and 0s like this:

times <- seq(0, 20 * pi, pi / 6)
probs <- sin(times) * 0.5 + 0.5
```
<p>Our probability of getting a 1 at each time step looks like this:</p>
```plot(times, probs, type = "l")
```
<p><img src="https://i.imgur.com/E3Anvt3.png" alt="" /></p>
<p>And we can generate a sample like this:</p>
<pre class="lang-r prettyprint-override"><code>set.seed(1)
samp <- rbinom(length(times), 1, probs)

samp
#>   [1] 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0
#>  [38] 1 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1
#>  [75] 1 1 1 1 1 0 0 0 0 1 0 0 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0 1 1
#> [112] 1 1 0 0 0 0 0 0 0 1
</code>```

And we can demonstrate that acf correctly identifies the autocorrelation:

```<code>acf(samp)
</code>```

Created on 2022-02-12 by the reprex package (v2.0.1)

Body:
Hi supposed I have a vector consisting of 0's and 1's; will the default acf function be able to calculate this correctly?

set.seed ( 12 )
bin = sample(c(0,1), replace=TRUE, size=5000)
acf (bin )

Body:
Yes. Your example doesn't work because it is completely random. But we can create a binomial sample with an oscillating probability of 1s and 0s like this:

times <- seq(0, 20 * pi, pi / 6)
probs <- sin(times) * 0.5 + 0.5

Our probability of getting a 1 at each time step looks like this:

plot(times, probs, type = "l")

And we can generate a sample like this:

set.seed(1)
samp <- rbinom(length(times), 1, probs)

samp
#>   [1] 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0
#>  [38] 1 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1
#>  [75] 1 1 1 1 1 0 0 0 0 1 0 0 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0 1 1
#> [112] 1 1 0 0 0 0 0 0 0 1

And we can demonstrate that acf correctly identifies the autocorrelation:

acf(samp)

Created on 2022-02-12 by the reprex package (v2.0.1)


答:
Since you already hav the list sorted properly, a simple way to do this is to use itertools.groupby to grab the first element of each group in a list comprehension:

```<code>from itertools import groupby

l= [
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

[next(g) for k, g in groupby(l, key=lambda d: d['id'])]

# [{'id': '23', 'type': 'car', 'price': '445'},
#  {'id': '125', 'type': 'truck', 'price': '998'},
#  {'id': '87', 'type': 'bike', 'price': '50'}]
</code>```

Title: Remove duplicates from list of lists by column value

Body:
Since you already hav the list sorted properly, a simple way to do this is to use itertools.groupby to grab the first element of each group in a list comprehension:

from itertools import groupby

l= [
    {'id': '23', 'type': 'car', 'price': '445'},
    {'id': '23', 'type': 'car', 'price': '78'},
    {'id': '23', 'type': 'car', 'price': '34'},
    {'id': '125', 'type': 'truck', 'price': '998'},
    {'id': '125', 'type': 'truck', 'price': '722'},
    {'id': '125', 'type': 'truck', 'price': '100'},
    {'id': '87', 'type': 'bike', 'price': '50'},
]

[next(g) for k, g in groupby(l, key=lambda d: d['id'])]

# [{'id': '23', 'type': 'car', 'price': '445'},
#  {'id': '125', 'type': 'truck', 'price': '998'},
#  {'id': '87', 'type': 'bike', 'price': '50'}]


问:
Using the global object as storage
I have made an application that is receiving location data from a few web clients on regular intervals. I made a quick implementation using couchdb, but as couchdb creates a new revision for each update and the data is quite frequently updated, it consumed a lot of disk space whereas the historic data was of little significance. I looked into MongoDB instead, but as I was thinking how I could make the MongoDB implementation, I had another idea:

The global object is in the process scope, so it can be used to share data between sessions. Persistence beyond session is not required, so I dropped the database completely and stored all the data in the global object (and persisted some data for user convenience in the HTML5 localStorage using javascript). The complexity of the backend was greatly reduced, and the solution felt somewhat elegant, but I still feel like I need to take a shower...

So to my question: Are there any obvious pitfalls with this solution that I haven't thought about?

答:
Congrats you have rediscovered memcache. (I did it twice)
If you need to store this data then you actually should to save it to db, because server app restart will erase all data from RAM. So actually is better to use memcache and asynchronous writing to db.</p>

Title: Using the global object as storage


问:
Pygame (changing simple rectangle to image)
So I don't know how to turn the rectangle representing the player into an image (spaceship). I know it must be simple, but after a few hours with this I'm a little frustrated, so I'm looking for help :(

```<code>bg_color = pygame.Color('black')
text_color = pygame.Color('darkgrey')
obstacles_color = pygame.Color('darkred')
player_color = pygame.Color('yellow')

fps = 60

window_height = 1200
window_width = 1200

player_speed = 4
player_size = 8
player_max_up = 125

obstacle_spawn_rate = 1
obstacle_min_size = 3
obstacle_max_size = 6
obstacle_min_speed = 2
obstacle_max_speed = 2

class Player:
    def __init__(self):
        self.size = player_size
        self.speed = player_speed
        self.color = player_color
        self.position = (window_width / 2, (window_height - (window_height / 10)))

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self, x, y):
        newX = self.position[0] + x
        newY = self.position[1] + y
        if newX < 0 or newX > window_width - player_size:
            newX = self.position[0]
        if newY < window_height - player_max_up or newY > window_height - player_size:
            newY = self.position[0]
        self.position = (newX, newY)

    def collision_detection(self, rect):
        r = self.get_rect()
        return r.colliderect(rect)

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class Obstacles:
    def __init__(self):
        self.size = random.randint(obstacle_min_size, obstacle_max_size)
        self.speed = random.randint(obstacle_min_speed, obstacle_max_speed)
        self.color = obstacles_color
        self.position = (random.randint(0, window_width - self.size), 0 - self.size)

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self):
        self.position = (self.position[0], self.position[1] + self.speed)

    def is_off_window(self):
        return self.position[1] > window_height

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class World:
    def __init__(self):
        self.reset()

    def reset(self):
        self.player = Player()
        self.obstacles = []
        self.gameOver = False
        self.score = 0
        self.obstacles_counter = 0
        self.moveUp = False
        self.moveDown = False
        self.moveLeft = False
        self.moveRight = False

    def is_game_over(self):
        return self.gameOver

    def update(self):
        self.score += 1

        if self.moveUp:
            self.player.move(0, - player_speed)
        if self.moveUp:
            self.player.move(0, player_speed)
        if self.moveLeft:
            self.player.move(-player_speed, 0)
        if self.moveRight:
            self.player.move(player_speed, 0)

        for each in self.obstacles:
            each.move()
            if self.player.collision_detection(each.get_rect()):
                self.gameOver = True
            if each.is_off_window():
                self.obstacles.remove(each)

        self.obstacles_counter += 1
        if self.obstacles_counter > obstacle_spawn_rate:
            self.obstacles_counter = 0
            self.obstacles.append(Obstacles())

    def draw(self, surface):
        self.player.draw(surface)
        for each in self.obstacles:
            each.draw(surface)

    def movement_keys(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.moveUp = True
            if event.key == pygame.K_DOWN:
                self.moveDown = True
            if event.key == pygame.K_LEFT:
                self.moveLeft = True
            if event.key == pygame.K_RIGHT:
                self.moveRight = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                 self.moveUp = False
            if event.key == pygame.K_DOWN:
                 self.moveDown = False
            if event.key == pygame.K_LEFT:
                 self.moveLeft = False
            if event.key == pygame.K_RIGHT:
                 self.moveRight = False

def run():
    pygame.init()
    clock = pygame.time.Clock()
    window = pygame.display.set_mode((window_height, window_width))
    pygame.display.set_caption("Avoid Obstacles")
    surface = pygame.Surface(window.get_size())
    surface = surface.convert()

    world = World()

    font = pygame.font.SysFont("Times", 35, "bold")

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == ord("r"):
                world.reset()
            else:
                world.movement_keys(event)

        if not world.is_game_over():
            world.update()

        window.fill(bg_color)
        clock.tick(fps)
        world.draw(window)

        surface.blit(surface, (0, 0))
        text = font.render("Score {0}".format(world.score), 1, text_color)
        window.blit(text, (1, 1))
        if world.is_game_over():
            end = font.render("The end of your journey", 1, text_color)
            window.blit(end, (window_width / 2 - 220, window_height / 2))
            restart = font.render("Hit R to reset", 1, text_color)
            window.blit(restart, (window_width / 2 - 120, window_height / 2 + 45))
        pygame.display.update()

if __name__ == '__main__':
    run()
    pygame.quit()
</code>```

I tried changing the draw function in the Player class, but still couldn't figure out how to do it correctly. I'm drawing an image of the spaceship on the screen/window, but I can't get it to move to the player rectangle.

答:
The 'draw' family of functions are convenience functions that create Surface objects and then paint pixels on it that correspond to basic shapes (like circles, rectangles etc, filled or otherwise).

Instead, you need to create a Surface where the pixels have been initialised via an image. For this, you need the "image" family of functions (see https://www.pygame.org/docs/ref/image.html for image functions).

Other than that, everything in pygame is a surface, and you're manipulating and updating surfaces on the display, so your code should not change, whether your surfaces were initialised via 'draw' or 'image'.

Body:
So I don't know how to turn the rectangle representing the player into an image (spaceship). I know it must be simple, but after a few hours with this I'm a little frustrated, so I'm looking for help :(

bg_color = pygame.Color('black')
text_color = pygame.Color('darkgrey')
obstacles_color = pygame.Color('darkred')
player_color = pygame.Color('yellow')

fps = 60

window_height = 1200
window_width = 1200

player_speed = 4
player_size = 8
player_max_up = 125

obstacle_spawn_rate = 1
obstacle_min_size = 3
obstacle_max_size = 6
obstacle_min_speed = 2
obstacle_max_speed = 2

class Player:
    def __init__(self):
        self.size = player_size
        self.speed = player_speed
        self.color = player_color
        self.position = (window_width / 2, (window_height - (window_height / 10)))

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self, x, y):
        newX = self.position[0] + x
        newY = self.position[1] + y
        if newX < 0 or newX > window_width - player_size:
            newX = self.position[0]
        if newY < window_height - player_max_up or newY > window_height - player_size:
            newY = self.position[0]
        self.position = (newX, newY)

    def collision_detection(self, rect):
        r = self.get_rect()
        return r.colliderect(rect)

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class Obstacles:
    def __init__(self):
        self.size = random.randint(obstacle_min_size, obstacle_max_size)
        self.speed = random.randint(obstacle_min_speed, obstacle_max_speed)
        self.color = obstacles_color
        self.position = (random.randint(0, window_width - self.size), 0 - self.size)

    def draw(self, surface):
        r = self.get_rect()
        pygame.draw.rect(surface, self.color, r)

    def move(self):
        self.position = (self.position[0], self.position[1] + self.speed)

    def is_off_window(self):
        return self.position[1] > window_height

    def get_rect(self):
        return pygame.Rect(self.position, (self.size, self.size))

class World:
    def __init__(self):
        self.reset()

    def reset(self):
        self.player = Player()
        self.obstacles = []
        self.gameOver = False
        self.score = 0
        self.obstacles_counter = 0
        self.moveUp = False
        self.moveDown = False
        self.moveLeft = False
        self.moveRight = False

    def is_game_over(self):
        return self.gameOver

    def update(self):
        self.score += 1

        if self.moveUp:
            self.player.move(0, - player_speed)
        if self.moveUp:
            self.player.move(0, player_speed)
        if self.moveLeft:
            self.player.move(-player_speed, 0)
        if self.moveRight:
            self.player.move(player_speed, 0)

        for each in self.obstacles:
            each.move()
            if self.player.collision_detection(each.get_rect()):
                self.gameOver = True
            if each.is_off_window():
                self.obstacles.remove(each)

        self.obstacles_counter += 1
        if self.obstacles_counter > obstacle_spawn_rate:
            self.obstacles_counter = 0
            self.obstacles.append(Obstacles())

    def draw(self, surface):
        self.player.draw(surface)
        for each in self.obstacles:
            each.draw(surface)

    def movement_keys(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.moveUp = True
            if event.key == pygame.K_DOWN:
                self.moveDown = True
            if event.key == pygame.K_LEFT:
                self.moveLeft = True
            if event.key == pygame.K_RIGHT:
                self.moveRight = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                 self.moveUp = False
            if event.key == pygame.K_DOWN:
                 self.moveDown = False
            if event.key == pygame.K_LEFT:
                 self.moveLeft = False
            if event.key == pygame.K_RIGHT:
                 self.moveRight = False

def run():
    pygame.init()
    clock = pygame.time.Clock()
    window = pygame.display.set_mode((window_height, window_width))
    pygame.display.set_caption("Avoid Obstacles")
    surface = pygame.Surface(window.get_size())
    surface = surface.convert()

    world = World()

    font = pygame.font.SysFont("Times", 35, "bold")

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == ord("r"):
                world.reset()
            else:
                world.movement_keys(event)

        if not world.is_game_over():
            world.update()

        window.fill(bg_color)
        clock.tick(fps)
        world.draw(window)

        surface.blit(surface, (0, 0))
        text = font.render("Score {0}".format(world.score), 1, text_color)
        window.blit(text, (1, 1))
        if world.is_game_over():
            end = font.render("The end of your journey", 1, text_color)
            window.blit(end, (window_width / 2 - 220, window_height / 2))
            restart = font.render("Hit R to reset", 1, text_color)
            window.blit(restart, (window_width / 2 - 120, window_height / 2 + 45))
        pygame.display.update()

if __name__ == '__main__':
    run()
    pygame.quit()

I tried changing the draw function in the Player class, but still couldn't figure out how to do it correctly. I'm drawing an image of the spaceship on the screen/window, but I can't get it to move to the player rectangle.


问:
Keep file in a Git repo, but don't track changes
I need to include some files in my GitHub repo, but not track changes on them. How can I accomplish this? An example use case is for a file that includes sensitive user information, such as login credentials.

For example, I deploy a new installation of this framework to a new client, I want the following files to be downloaded (they have default values CHANGEME) and I just have to make changes specific to this client (database credentials, email address info, custom CSS).

```<code>// The production config files. I want the files but they need to be updated to specific client needs
application/config/production/config.php
application/config/production/database.php
application/config/production/tank_auth.php
// Index page, defines the environment (production|development)
/index.php
// All of the css/js cache (keep the folder but not the contents)
/assets/cache/*
// Production user based styling (color, fonts etc) needs to be updated specific to client needs
/assets/frontend/css/user/frontend-user.css
</code>```

Currently if I run

```<code>git clone git@github.com:user123/myRepo.git httpdocs
</code>```

and then edit the files above, all is great. Until I release a hotfix or patch and run git pull. All of my changes are then overwritten.

答:
Make sure to add "full path for filename" (relative path from root)

git update-index --skip-worktree FILENAME.

If you do not give the full path for the file. It will give an error

fatal: Unable to mark file response.json

Body:
I need to include some files in my GitHub repo, but not track changes on them. How can I accomplish this? An example use case is for a file that includes sensitive user information, such as login credentials.

For example, I deploy a new installation of this framework to a new client, I want the following files to be downloaded (they have default values CHANGEME) and I just have to make changes specific to this client (database credentials, email address info, custom CSS).

// The production config files. I want the files but they need to be updated to specific client needs
application/config/production/config.php
application/config/production/database.php
application/config/production/tank_auth.php
// Index page, defines the environment (production|development)
/index.php
// All of the css/js cache (keep the folder but not the contents)
/assets/cache/*
// Production user based styling (color, fonts etc) needs to be updated specific to client needs
/assets/frontend/css/user/frontend-user.css

Currently if I run

git clone git@github.com:user123/myRepo.git httpdocs

and then edit the files above, all is great. Until I release a hotfix or patch and run git pull. All of my changes are then overwritten.


问:
Flask class import error - Error: While importing 'app', an ImportError was raised
I have a flask app and I have written a custom api class to handle some api connections that Im trying to use in my flask app

The custom class is as follows:

import request
import base64
import os
from dotenv import load_dotenv

class Rotaready:

    def __init__(self):
        self.org_id = 'MPRJ'
        self.token = None
```
<p>The flask app looks like so:</p>
<pre class="lang-py prettyprint-override"><code>import os
import logging
from rotaready import Rotaready
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Message, Mail
from flask_cors import CORS, cross_origin
from flask_bcrypt import Bcrypt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'

app.config['MAIL_SERVER'] = 'smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = 'username'
app.config['MAIL_PASSWORD'] = 'password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['JWT_SECRET_KEY'] = '_5#y2L"F4Q8zxec]/'

mail = Mail(app)
db = SQLAlchemy(app)
jwt = JWTManager(app)
cors = CORS(app)
bcrypt = Bcrypt(app)

logging.basicConfig(filename='demo.log', level=logging.DEBUG)
</code>```

I then load into pipenv shell and run flask run and I get

```<code>Error: While importing 'app', an ImportError was raised
</code>```

I try and use the class as follows

```<code>@app.route('/test/rotaready', methods=['GET'])
def test_rotaready():
    rotaready = Rotaready()
    token = rotaready.create_connection()
    if token:
        return jsonify(message='Token Created Successfully'), 200
    else:
        return jsonify(message='Token issue'), 404
</code>```

my pip file is as follows:

```<code>[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]
flask = "*"
python-dotenv = "*"
mysql-connector-python = "*"
flask-mysqldb = "*"
flask-jwt-extended = "*"
sqlalchemy = "*"
flask-sqlalchemy = "*"
flask-mail = "*"
flask-cors = "*"
bcrypt-flask = "*"
requests = "*"

[dev-packages]

[requires]
python_version = "3.8"
</code>```

This is the output on the error and have no stack trace

```<code>E7440:/home/graham/Documents/development/kojo-backend-app# flask run  * Environment: development  * Debug mode: on Usage: flask run [OPTIONS] Try 'flask run --help' for help.  Error: While importing 'app', an ImportError was raised.
</code>```

I hope thats all the information you will need

答:
So it turns out it after running python app.py I had an error on a f string and that was causing the import error!

So flask run for debugging wasnt great and running

```<code>python app.py
</code>```

Was the way forward to debug any errors

Body:
I have a flask app and I have written a custom api class to handle some api connections that Im trying to use in my flask app

The custom class is as follows:

import request
import base64
import os
from dotenv import load_dotenv

class Rotaready:

    def __init__(self):
        self.org_id = 'MPRJ'
        self.token = None

The flask app looks like so:

import os
import logging
from rotaready import Rotaready
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Message, Mail
from flask_cors import CORS, cross_origin
from flask_bcrypt import Bcrypt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'

app.config['MAIL_SERVER'] = 'smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = 'username'
app.config['MAIL_PASSWORD'] = 'password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['JWT_SECRET_KEY'] = '_5#y2L"F4Q8zxec]/'

mail = Mail(app)
db = SQLAlchemy(app)
jwt = JWTManager(app)
cors = CORS(app)
bcrypt = Bcrypt(app)

logging.basicConfig(filename='demo.log', level=logging.DEBUG)

I then load into pipenv shell and run flask run and I get

Error: While importing 'app', an ImportError was raised

I try and use the class as follows

@app.route('/test/rotaready', methods=['GET'])
def test_rotaready():
    rotaready = Rotaready()
    token = rotaready.create_connection()
    if token:
        return jsonify(message='Token Created Successfully'), 200
    else:
        return jsonify(message='Token issue'), 404

my pip file is as follows:

[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]
flask = "*"
python-dotenv = "*"
mysql-connector-python = "*"
flask-mysqldb = "*"
flask-jwt-extended = "*"
sqlalchemy = "*"
flask-sqlalchemy = "*"
flask-mail = "*"
flask-cors = "*"
bcrypt-flask = "*"
requests = "*"

[dev-packages]

[requires]
python_version = "3.8"

This is the output on the error and have no stack trace

E7440:/home/graham/Documents/development/kojo-backend-app# flask run  * Environment: development  * Debug mode: on Usage: flask run [OPTIONS] Try 'flask run --help' for help.  Error: While importing 'app', an ImportError was raised.

I hope thats all the information you will need

Body:
So it turns out it after running python app.py I had an error on a f string and that was causing the import error!

So flask run for debugging wasnt great and running

python app.py

Was the way forward to debug any errors


问:
Can you force activerecord associations to update without saving them?
I have a couple models which are associated with the has_many belongs_to pair.  For the sake of demonstration, a client has one server but a server has many clients.  I might do something like this:

```<code>client1.server = the_server
client2.server = the_server
client3.server = the_server
</code>```

My actual application is quite a bit more complex than this, but the example will work for illustration.

I want to inspect the associations between these objects before I save them.  ActiveRecord doesn't update their information until they are saved though.  In the example above, the_server has no idea who client1, client2, or client3 are until one of them gets saved.  I'm sure that this helps active_record's efficiency, but it leaves model instances in memory in an inconsistent state.

Is there anything I can call on the clients or on the server that will cause them to update their states?

答:
If you start off like this:

```<code>client1 = the_server.clients.build(:name => 'a client', ...)
</code>```

Then you should get what you're looking for I think.

EDIT:

Oops, I re-read your post and realized that the_server hasn't been saved yet either.  In that case perhaps:

```<code>client1.server = the_server
the_server.clients << client1
</code>```

(be aware that this will save client1 if the_server is already saved)

or:

```<code>the_server.clients.build(:name => 'some client', ..., :server => the_server)
</code>```

A bit redundant so perhaps there's a better way out there.

ContentLicense: CC BY-SA 2.5

Body:
I have a couple models which are associated with the has_many belongs_to pair.  For the sake of demonstration, a client has one server but a server has many clients.  I might do something like this:

client1.server = the_server
client2.server = the_server
client3.server = the_server

My actual application is quite a bit more complex than this, but the example will work for illustration.

I want to inspect the associations between these objects before I save them.  ActiveRecord doesn't update their information until they are saved though.  In the example above, the_server has no idea who client1, client2, or client3 are until one of them gets saved.  I'm sure that this helps active_record's efficiency, but it leaves model instances in memory in an inconsistent state.

Is there anything I can call on the clients or on the server that will cause them to update their states?

Body:
If you start off like this:

client1 = the_server.clients.build(:name => 'a client', ...)

Then you should get what you're looking for I think.

EDIT:

Oops, I re-read your post and realized that the_server hasn't been saved yet either.  In that case perhaps:

client1.server = the_server
the_server.clients << client1

(be aware that this will save client1 if the_server is already saved)

or:

the_server.clients.build(:name => 'some client', ..., :server => the_server)

A bit redundant so perhaps there's a better way out there.

OwnerDisplayName: Jordan Brough

LastEditorDisplayName: Jordan Brough


问:
Gradle - getting the latest release version of a dependency
What would be the easiest way to tell Gradle the following:

Retrieve 'junit' dependency and take its latest 'release' version.

Managing Maven and Ivy repositories is sort of new to me. I tried the following steps and they result in Could not resolve dependency ... error:

Write compile "junit:junit:latest.release" with repositories set to only mavenCentral() (however, it works if I say "junit:junit:4.10").

Write compile "junit:junit:latest.release" with repository set the following way:

```<code>ivy {
    // I also tried 'http://maven.org' and other possible variants.
    url "http://repo1.maven.org"
    layout "maven"
}
</code>```

Attempted to use Spring Source Ivy repository:

```<code>ivy {
    artifactPattern "http://repository.springsource.com/ivy/libraries/release/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]"
    ivyPattern "http://repository.springsource.com/ivy/libraries/release/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]"
}
</code>```

Maybe I misunderstand something. Why would getting the latest version of the dependency be such a hard task?

答:
Another similar notation for Kotlin DSL (build.gradle.kts):

dependencies {
    implementation("or.jsoup", "jsoup") {
        version {
            require("1.14.+")
        }
    }
    // OR simply
    // implementation("or.jsoup:jsoup:1.14.+")
}
```

Read more about this in Gradle documentations.

An excerpt from the docs:

A dynamic version can be either a version range (e.g. 2.+) or it can be a placeholder for the latest version available e.g. latest.integration.

Body:
What would be the easiest way to tell Gradle the following:

Retrieve 'junit' dependency and take its latest 'release' version.

Managing Maven and Ivy repositories is sort of new to me. I tried the following steps and they result in Could not resolve dependency ... error:

Write compile "junit:junit:latest.release" with repositories set to only mavenCentral() (however, it works if I say "junit:junit:4.10").

Write compile "junit:junit:latest.release" with repository set the following way:

ivy {
    // I also tried 'http://maven.org' and other possible variants.
    url "http://repo1.maven.org"
    layout "maven"
}

Attempted to use Spring Source Ivy repository:

ivy {
    artifactPattern "http://repository.springsource.com/ivy/libraries/release/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]"
    ivyPattern "http://repository.springsource.com/ivy/libraries/release/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]"
}

Maybe I misunderstand something. Why would getting the latest version of the dependency be such a hard task?

Body:
Another similar notation for Kotlin DSL (build.gradle.kts):

dependencies {
    implementation("or.jsoup", "jsoup") {
        version {
            require("1.14.+")
        }
    }
    // OR simply
    // implementation("or.jsoup:jsoup:1.14.+")
}

Read more about this in Gradle documentations.

An excerpt from the docs:

A dynamic version can be either a version range (e.g. 2.+) or it can be a placeholder for the latest version available e.g. latest.integration.


问:
Width transition tailwind CSS
I would like to show and slide an element from the left to the right of the page. To do so, I hide it by default. When a button is clicked, the ul element is displayed and its width goes from 0px to 100vw. I also added a transition on the width property of the ul element.

HTML:

```<code><!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>
  <ul id="hidden_nav" class="hidden w-0 h-screen bg-red-50 mt-10 transition-[width] duration-1000">
    <li> Item </li>
    <li> Item </li>
  </ul>
</body>
</html>
</code>```

JS:

```<code>const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('hidden');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});
</code>```

Codepen link:

https://codepen.io/Okumak/pen/qBVjwdY

Yet, I cannot see any transition going on and I don't get why.

答:
It will never work with a hidden class. An alternative solution would be opacity.

const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('opacity-0');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>
  <ul id="hidden_nav" class="opacity-0 w-0 h-screen bg-red-50 mt-10 transition-[width] duration-1000">
    <li> Item </li>
    <li> Item </li>
  </ul>
</body>
</html></code>```

Just look after the height. It still takes up space when hidden, just in case you want to toggle it as well then you can do so.

Title: Width transition tailwind CSS

Body:
I would like to show and slide an element from the left to the right of the page. To do so, I hide it by default. When a button is clicked, the ul element is displayed and its width goes from 0px to 100vw. I also added a transition on the width property of the ul element.

HTML:

<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>

 Item

 Item

JS:

const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('hidden');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});

Codepen link:

https://codepen.io/Okumak/pen/qBVjwdY

Yet, I cannot see any transition going on and I don't get why.

Body:
It will never work with a hidden class. An alternative solution would be opacity.

const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('opacity-0');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>
  <ul id="hidden_nav" class="opacity-0 w-0 h-screen bg-red-50 mt-10 transition-[width] duration-1000">
    <li> Item </li>
    <li> Item </li>
  </ul>
</body>
</html>

Just look after the height. It still takes up space when hidden, just in case you want to toggle it as well then you can do so.


问:
Symfony cache:clear in Azure web app with GitHub Actions
I am deploying a symfony application to an Azure Linux PHP 7.4 web app.  I used the approach suggested in How to archive files in artifact for github workflow actions in order to fix this warning? to streamline the deployment.

So everything is working well, but occasionally the site fails.  I tracked it down to a stale cache.  To fix the problem I have to SSH into the web app and clear the cache using

```<code>$ php bin/console cache:clear
</code>```

Looking in detail at the Github actions build and deploy log, I see that cache:clear is executed on the build VM, which is not helpful.

I am using the standard php build and deploy script with the zip/unzip steps added...

```<code># Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions

name: Build and deploy PHP app to Azure Web App - xxx

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.4'

      - name: Check if composer.json exists
        id: check_files
        uses: andstor/file-existence-action@v1
        with:
          files: 'composer.json'

      - name: Run composer install if composer.json exists
        if: steps.check_files.outputs.files_exists == 'true'
        run: composer validate --no-check-publish && composer install --prefer-dist --no-progress

      - name: Zip artifact for deployment
        run: zip -r release.zip * .env .htaccess public/.htaccess

      - name: Upload artifact for deployment job
        uses: actions/upload-artifact@v2
        with:
          name: php-app
          path: release.zip

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'staging'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

    steps:
      - name: Download artifact from build job
        uses: actions/download-artifact@v2
        with:
          name: php-app

      - name: Unzip artifact for deployment
        run: unzip release.zip

      - name: 'Deploy to Azure Web App'
        uses: azure/webapps-deploy@v2
        id: deploy-to-webapp
        with:
          app-name: 'xxxx'
          slot-name: 'staging'
          publish-profile: ${{ secrets.AZUREAPPSERVICE_xxxxx }}
          package: .

</code>```

How do I get the clear cache command to work after deployment to the web app?

答:
Right...

It turns out the way to clear the cache is very simple.  Use the cache clear command as the "startup command"

So I deploy and SSH into the web app and check /home/site/wwwroot/var/cache/staging and voila! all the file are newly created!

This has occurred to me at the beginning, but it really seemed like a kluge.  I really wanted a cleaner way to do this.  I tried adding the startup command to the deployment script but got this error...

So I cannot add startup command because there is a publish profile.

So why did such a simple problem take so long to answer on SO? More than one suggested answers that were completely irrelevant.  All these answers had in common with my issue were words like "cache" and "php".

Body:
I am deploying a symfony application to an Azure Linux PHP 7.4 web app.  I used the approach suggested in How to archive files in artifact for github workflow actions in order to fix this warning? to streamline the deployment.

So everything is working well, but occasionally the site fails.  I tracked it down to a stale cache.  To fix the problem I have to SSH into the web app and clear the cache using

$ php bin/console cache:clear

Looking in detail at the Github actions build and deploy log, I see that cache:clear is executed on the build VM, which is not helpful.

I am using the standard php build and deploy script with the zip/unzip steps added...

# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions

name: Build and deploy PHP app to Azure Web App - xxx

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '7.4'

      - name: Check if composer.json exists
        id: check_files
        uses: andstor/file-existence-action@v1
        with:
          files: 'composer.json'

      - name: Run composer install if composer.json exists
        if: steps.check_files.outputs.files_exists == 'true'
        run: composer validate --no-check-publish && composer install --prefer-dist --no-progress

      - name: Zip artifact for deployment
        run: zip -r release.zip * .env .htaccess public/.htaccess

      - name: Upload artifact for deployment job
        uses: actions/upload-artifact@v2
        with:
          name: php-app
          path: release.zip

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'staging'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

    steps:
      - name: Download artifact from build job
        uses: actions/download-artifact@v2
        with:
          name: php-app

      - name: Unzip artifact for deployment
        run: unzip release.zip

      - name: 'Deploy to Azure Web App'
        uses: azure/webapps-deploy@v2
        id: deploy-to-webapp
        with:
          app-name: 'xxxx'
          slot-name: 'staging'
          publish-profile: ${{ secrets.AZUREAPPSERVICE_xxxxx }}
          package: .

How do I get the clear cache command to work after deployment to the web app?


问:
How to find unicode character class in PHP
I am having hard times finding a way to get the unicode class of a char.

list of unicode classes: https://www.php.net/manual/en/regexp.reference.unicode.php

The desired function in python: https://docs.python.org/3/library/unicodedata.html#unicodedata.category

I just want the PHP equivalent to this python function.

For example, if I called the x function like this: x('-') it would return Pd because Pd is the class hyphen belongs to.

Thanks.

答:
A possible way is to use IntlChar::charType. Unfortunately, this method returns only an int, but this int is a constant defined in the IntlChar class. All the constants for the 30 categories are in a 0 to 29 range (no gaps). Conclusion, all you have to do is to build a indexed array that follows the same order:

```<code>$shortCats = [
    'Cn', 'Lu', 'Ll', 'Lt', 'Lm', 'Lo',
    'Mn', 'Me', 'Mc', 'Nd', 'Nl', 'No',
    'Zs', 'Zl', 'Zp', 'Cc', 'Cf', 'Co',
    'Cs', 'Pd', 'Ps', 'Pe', 'Pc', 'Po',
    'Sm', 'Sc', 'Sk', 'So', 'Pi', 'Pf'
];

echo $shortCats[IntlChar::charType('-')]; //Pd
</code>```

Notice: If you are afraid that the numeric values defined in the class change in the futur and want to be more rigorous, You can also write the array this way:

```<code>$shortCats = [
    IntlChar::CHAR_CATEGORY_UNASSIGNED => 'Cn',
    IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER => 'Lu',
    IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER => 'Ll',
    IntlChar::CHAR_CATEGORY_TITLECASE_LETTER => 'Lt',
    // etc.
];
</code>```

Body:
A possible way is to use IntlChar::charType. Unfortunately, this method returns only an int, but this int is a constant defined in the IntlChar class. All the constants for the 30 categories are in a 0 to 29 range (no gaps). Conclusion, all you have to do is to build a indexed array that follows the same order:

$shortCats = [
    'Cn', 'Lu', 'Ll', 'Lt', 'Lm', 'Lo',
    'Mn', 'Me', 'Mc', 'Nd', 'Nl', 'No',
    'Zs', 'Zl', 'Zp', 'Cc', 'Cf', 'Co',
    'Cs', 'Pd', 'Ps', 'Pe', 'Pc', 'Po',
    'Sm', 'Sc', 'Sk', 'So', 'Pi', 'Pf'
];

echo $shortCats[IntlChar::charType('-')]; //Pd

Notice: If you are afraid that the numeric values defined in the class change in the futur and want to be more rigorous, You can also write the array this way:

$shortCats = [
    IntlChar::CHAR_CATEGORY_UNASSIGNED => 'Cn',
    IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER => 'Lu',
    IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER => 'Ll',
    IntlChar::CHAR_CATEGORY_TITLECASE_LETTER => 'Lt',
    // etc.
];


问:
sortwith one of the POJO values?
I have random pojo values, and I want to sort by one of the POJO values, the structure of the values I want to sort is as follows: A-1, A-2, A-3, A-4, A-5, .. .

I've tried to sort it but the value is really in order only between A-1 to A-9, while the value for A-10 is always under A-1.

here's the code I use:

```<code>temp.sortWith { lhs, rhs ->
  rhs?.blok_kamar?.let {
  lhs?.blok_kamar?.compareTo(
    it, false
  )}!!
}
</code>```

Please help.

答:
Base on your code I do not know what temp actually is, so here is an idea to give you a start, based on a list:</p>
```<code>val result = list
  .sortedBy {
    it.id.substringBefore("-") + "-" + it.id.substringAfter("-").padStart(3, '0')
  }
</code>```

Title: sortwith one of the POJO values?

Body:
I have random pojo values, and I want to sort by one of the POJO values, the structure of the values I want to sort is as follows: A-1, A-2, A-3, A-4, A-5, .. .

I've tried to sort it but the value is really in order only between A-1 to A-9, while the value for A-10 is always under A-1.

here's the code I use:

temp.sortWith { lhs, rhs ->
  rhs?.blok_kamar?.let {
  lhs?.blok_kamar?.compareTo(
    it, false
  )}!!
}

Please help.

Body:
Base on your code I do not know what temp actually is, so here is an idea to give you a start, based on a list:

val result = list
  .sortedBy {
    it.id.substringBefore("-") + "-" + it.id.substringAfter("-").padStart(3, '0')
  }


问:
How would I resolve 422 this 422 error during POST?
I'm working on my React task.
I've tried create new product and send it with post method. I use fetch and axios both. In both cases I got error 422.
Here is Swager : https://newdemostock.gopos.pl/doc/swagger-ui/index.html?configUrl=%2Fv3%2Fapi-docs%2Fswagger-config&urls.primaryName=internal%20ajax&fbclid=IwAR0GUn4T42DxkREmZ6TNLdK5UlQYFPqEQltpmfCQ6iUBVDTwwIRBhoARoA8

Login: zadanie@gopos.pl

password: test

I've tried this endpoints : https://newdemostock.gopos.pl/ajax/219/products/create

 Authorization: fd9ba9e1-0788-4e8f-ac46-a43df43e205e

 OrganizationId : 219

Maybe I should have used another eindpoit?
Does anyone know how I can solve this problem?
```<code>const NewProduct = () => {

  const product = {
    name: "test",
    item_name: "test",
  };
  const axiosConfig = {
    headers: {
      Authorization: `fd9ba9e1-0788-4e8f-ac46-a43df43e205e`,
      "content-type": "application/json",
      Accept: "application/json",
      //   mode: "cors",
      //   credentials: "same-origin",
    },
  };

  const sendProduct = async () => {
    axios
      .post(
        "https://newdemostock.gopos.pl/ajax/219/products/create",
        product,
        axiosConfig
      )
      .then((res) => {
        console.log("RESPONSE RECEIVED: ", res);
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      });

    // fetch("https://newdemostock.gopos.pl/ajax/219/products/create", {
    //     credentials: "same-origin",
    //   method: "post",
    //   mode: "cors",
    //   headers: new Headers({
    //     Authorization: "fd9ba9e1-0788-4e8f-ac46-a43df43e205e",
    //     "Content-Type": "application/json",
    //     Accept: "application/json",
    //   }),
    //   body: JSON.stringify(product),
    // })
    //   .then((resp) => console.log(resp))
    //   .catch((err) => console.log(err));
  };

  return (
    <div>
      <button onClick={sendProduct}>Send</button>
    </div>
  );
};

</code>```

Here is a console.log

答:
422 error means the request is well formed but not processable. So it seems your requests are making it to the desired endpoint but the server is unable to process them there.

If you have access to the backend server I would recommend adding console.logs to the route you are trying to hit, hit it with postman or your local client and then check the server logs. If you don't have access to the server I would double check any documentation the server custodians have provided and maybe get in touch with them.

Body:
I'm working on my React task.
I've tried create new product and send it with post method. I use fetch and axios both. In both cases I got error 422.
Here is Swager : https://newdemostock.gopos.pl/doc/swagger-ui/index.html?configUrl=%2Fv3%2Fapi-docs%2Fswagger-config&urls.primaryName=internal%20ajax&fbclid=IwAR0GUn4T42DxkREmZ6TNLdK5UlQYFPqEQltpmfCQ6iUBVDTwwIRBhoARoA8

Login: zadanie@gopos.pl

password: test

I've tried this endpoints : https://newdemostock.gopos.pl/ajax/219/products/create

 Authorization: fd9ba9e1-0788-4e8f-ac46-a43df43e205e

 OrganizationId : 219

Maybe I should have used another eindpoit?
Does anyone know how I can solve this problem?

const NewProduct = () => {

  const product = {
    name: "test",
    item_name: "test",
  };
  const axiosConfig = {
    headers: {
      Authorization: `fd9ba9e1-0788-4e8f-ac46-a43df43e205e`,
      "content-type": "application/json",
      Accept: "application/json",
      //   mode: "cors",
      //   credentials: "same-origin",
    },
  };

  const sendProduct = async () => {
    axios
      .post(
        "https://newdemostock.gopos.pl/ajax/219/products/create",
        product,
        axiosConfig
      )
      .then((res) => {
        console.log("RESPONSE RECEIVED: ", res);
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      });

    // fetch("https://newdemostock.gopos.pl/ajax/219/products/create", {
    //     credentials: "same-origin",
    //   method: "post",
    //   mode: "cors",
    //   headers: new Headers({
    //     Authorization: "fd9ba9e1-0788-4e8f-ac46-a43df43e205e",
    //     "Content-Type": "application/json",
    //     Accept: "application/json",
    //   }),
    //   body: JSON.stringify(product),
    // })
    //   .then((resp) => console.log(resp))
    //   .catch((err) => console.log(err));
  };

  return (

      <button onClick={sendProduct}>Send</button>

  );
};

Here is a console.log


问:
Java Generics not able to add child to List of parent
Why the below code is showing a compilation error. Doesn't extend mean it can take any subclass of Number, Also compilation is shown in the add method not while defining the List if it doesn't support this construct it should show compilation error while declaring.

```<code>List<? extends Number> list = new ArrayList<Integer>();
list.add(1)
</code>```

答:
Number literals are of type int. Using construction <? extends Number> you ensure, that you can pass only instances of Number class, or any classes, that Number inherits from (that is java.lang.Object). If you want to add subtypes of Number class, e.g. Integers you should use <? super Number> (it means: for whose Number is a super class)
You may want to use:

```<code>List<? super Number> list = new ArrayList<>();
list.add(1); //no compile-time error
</code>```

However, if you want to use elements of the collection, you may use them as instances of classes that extends Number class.

```<code>    List<? super Number> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    print(list);

    List<Object> objs = new ArrayList<>();
    objs.add(1);
    print(objs);

    List<Number> nums = new ArrayList<>();
    nums.add(1);
    print(nums);
}

public static void print(List<? super Number> list){ // you can pass List of instances of type Number or upper
    for(Object num: list){ // but you have to refer to them as Objects (it is an upper class of Number
        System.out.println(num);
    }
}
</code>```

Body:
Why the below code is showing a compilation error. Doesn't extend mean it can take any subclass of Number, Also compilation is shown in the add method not while defining the List if it doesn't support this construct it should show compilation error while declaring.

List<? extends Number> list = new ArrayList<Integer>();
list.add(1)

Body:
Number literals are of type int. Using construction <? extends Number> you ensure, that you can pass only instances of Number class, or any classes, that Number inherits from (that is java.lang.Object). If you want to add subtypes of Number class, e.g. Integers you should use <? super Number> (it means: for whose Number is a super class)
You may want to use:

List<? super Number> list = new ArrayList<>();
list.add(1); //no compile-time error

However, if you want to use elements of the collection, you may use them as instances of classes that extends Number class.

    List<? super Number> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    print(list);

    List<Object> objs = new ArrayList<>();
    objs.add(1);
    print(objs);

    List<Number> nums = new ArrayList<>();
    nums.add(1);
    print(nums);
}

public static void print(List<? super Number> list){ // you can pass List of instances of type Number or upper
    for(Object num: list){ // but you have to refer to them as Objects (it is an upper class of Number
        System.out.println(num);
    }
}


问:
Understanding java command line
Can someone help me understand what the java cmd line is doing below (broken down so easier to read)? I found this in our AV and have no clue what this cmd does as a whole.

From my googling, I found that for -DACTIVE=true, the -D sets a system property value. In this case, my understaning is that it's setting the ACTIVE value to true..?

I also understand that -classpath searches for class files in the specified directories.

Unfortunately for com.zerog.lax.LAX , I can't find what it does/is. Any help is apreciated.

```<code>    "C:\Users\user\AppData\Local\Temp\I1644615473\Windows\resource\jre\bin\java.exe" -DACTIVE=true

    -classpath "C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\IAClasses.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\Execute.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData\Execute.zip;

C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\Resource1.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData\Resource1.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData;"

    com.zerog.lax.LAX

    "C:/Users/user/AppData/Local/Temp/I1644615473/Windows/setup.lax"

    "C:/Users/user/AppData/Local/Temp/laxF375.tmp"
</code>```

答:
There are basically 4 parts to that:

The java command and its options (in this case, -D, which sets an arbitrary 'property'; the running program presumably will want this)

The classpath, which tells where to find all code that is required for execution. It is a list of directories and/or jar files.

The class to be run - in this case the class  com.zerog.lax.LAX, which is to be found somewhere in the places listed in classpath, and which must contain a suitable main() method.

Arguments to be passed to the main() of com.zerog.lax.LAX.

Title: Understanding java command line

Body:
Can someone help me understand what the java cmd line is doing below (broken down so easier to read)? I found this in our AV and have no clue what this cmd does as a whole.

From my googling, I found that for -DACTIVE=true, the -D sets a system property value. In this case, my understaning is that it's setting the ACTIVE value to true..?

I also understand that -classpath searches for class files in the specified directories.

Unfortunately for com.zerog.lax.LAX , I can't find what it does/is. Any help is apreciated.

    "C:\Users\user\AppData\Local\Temp\I1644615473\Windows\resource\jre\bin\java.exe" -DACTIVE=true

    -classpath "C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\IAClasses.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\Execute.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData\Execute.zip;

C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData\Resource1.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData\Resource1.zip;

    C:\Users\user\AppData\Local\Temp\I1644615473\InstallerData;

    C:\Users\user\AppData\Local\Temp\I1644615473\Windows\InstallerData;"

    com.zerog.lax.LAX

    "C:/Users/user/AppData/Local/Temp/I1644615473/Windows/setup.lax"

    "C:/Users/user/AppData/Local/Temp/laxF375.tmp"


问:
How to get $refs using Composition API in Vue3?
I am trying to get $refs in Vue 3 using Composition API. This is my template that has two child components and I need to get reference to one child component instance:

```<code><template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>
</code>```

In my code I use Template Refs: ref is a special attribute, that allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

If I use Options API then I don't have any problems:

```<code>  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }
</code>```

However, using Composition API I get error:

```<code>setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }
</code>```

Could anyone say how to do it using Composition API?

答:
```<code><template>
    <your-table ref="table"/>
    ...
</template>

<script>
import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      table.value.addEventListener('click', () => console.log("Event happened"))
    });

    return { table };
}
</script>
</code>```

Inside your other component you can interact with events you already registered on onMounted life cycle hook as with my example i've registered only one evnet

Body:
I am trying to get $refs in Vue 3 using Composition API. This is my template that has two child components and I need to get reference to one child component instance:

<template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>

In my code I use Template Refs: ref is a special attribute, that allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

If I use Options API then I don't have any problems:

  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }

However, using Composition API I get error:

setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }

Could anyone say how to do it using Composition API?

Body:
<template>
    <your-table ref="table"/>
    ...
</template>

<script>
import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
      table.value.addEventListener('click', () => console.log("Event happened"))
    });

    return { table };
}
</script>

Inside your other component you can interact with events you already registered on onMounted life cycle hook as with my example i've registered only one evnet


问:
How to avoid infinite loop in saga?
I cant understand why the code above runs infinite loop. My actions are different. Could u   please take a look?

```<code>import { call, put, takeLatest ,delay} from 'redux-saga/effects'
import { saveFetchedDevices,fetchDevicesRequest } from './devicesRedux'
import axios from "axios"

 const getDevices= () => {
     return axios.get("http://localhost:3131/devices")
}

function* fetchDevicesHandler(action) {
   try {
      const response = yield call(getDevices);
      yield delay(3000);
      yield put(saveFetchedDevices(response.data));

   } catch (e) {
       console.log(e)
   }
}

function* mySaga() {
  yield takeLatest(fetchDevicesRequest,fetchDevicesHandler);
}

export default mySaga;
</code>```

fetchDevicesRequest is dispatched from button. Then loop starts

delay is just to slow down infinite loop

答:
this is my redux file</p>
```<code>const createActionName = function(name) {
    return `app/devices/${name}`
}

const ADD_DEVICE = createActionName("ADD_DEVICE");
const UPDATE_DEVICE = createActionName("UPDATE_DEVICE");
const REMOVE_DEVICE = createActionName("REMOVE_DEVICE");
const SAVE_FETCHED_DEVICES = createActionName("SAVE_FETCHED_DEVICES");
const FETCH_DEVICES_REQUEST= createActionName("FETCH_DEVICES_REQUEST");

//action creators
export const addDevice = payload => ({ type: ADD_DEVICE, payload })
export const updateDevice = payload => ({ type: UPDATE_DEVICE, payload })
export const removeDevice = payload => ({ type: REMOVE_DEVICE, payload })
export const saveFetchedDevices = payload => ({ type: SAVE_FETCHED_DEVICES, payload })
export const fetchDevicesRequest = payload => ({ type: FETCH_DEVICES_REQUEST })

//selectors
export const getAllDevices = state => state.devices.data;

const reducer = function(statePart = [], action = {}) {

    switch(action.type) {
        case SAVE_FETCHED_DEVICES:
            return { data:  action.payload  }
        case ADD_DEVICE:
            return { ...statePart, data: [ ...statePart.data, action.payload ] }
        case UPDATE_DEVICE:
            return { ...statePart, data: [ ...statePart.data.map((device)=>device.id===action.payload.id?action.payload:device)] }
        case REMOVE_DEVICE:
            return { ...statePart, data: [ ...statePart.data.filter((device)=>device.id!==action.payload.id)] }
                default:
            return statePart
    }
}

export default reducer
</code>```

Title: How to avoid infinite loop in saga?

Body:
I cant understand why the code above runs infinite loop. My actions are different. Could u   please take a look?

import { call, put, takeLatest ,delay} from 'redux-saga/effects'
import { saveFetchedDevices,fetchDevicesRequest } from './devicesRedux'
import axios from "axios"

 const getDevices= () => {
     return axios.get("http://localhost:3131/devices")
}

function* fetchDevicesHandler(action) {
   try {
      const response = yield call(getDevices);
      yield delay(3000);
      yield put(saveFetchedDevices(response.data));

   } catch (e) {
       console.log(e)
   }
}

function* mySaga() {
  yield takeLatest(fetchDevicesRequest,fetchDevicesHandler);
}

export default mySaga;

fetchDevicesRequest is dispatched from button. Then loop starts

delay is just to slow down infinite loop

Body:
this is my redux file

const createActionName = function(name) {
    return `app/devices/${name}`
}

const ADD_DEVICE = createActionName("ADD_DEVICE");
const UPDATE_DEVICE = createActionName("UPDATE_DEVICE");
const REMOVE_DEVICE = createActionName("REMOVE_DEVICE");
const SAVE_FETCHED_DEVICES = createActionName("SAVE_FETCHED_DEVICES");
const FETCH_DEVICES_REQUEST= createActionName("FETCH_DEVICES_REQUEST");

//action creators
export const addDevice = payload => ({ type: ADD_DEVICE, payload })
export const updateDevice = payload => ({ type: UPDATE_DEVICE, payload })
export const removeDevice = payload => ({ type: REMOVE_DEVICE, payload })
export const saveFetchedDevices = payload => ({ type: SAVE_FETCHED_DEVICES, payload })
export const fetchDevicesRequest = payload => ({ type: FETCH_DEVICES_REQUEST })

//selectors
export const getAllDevices = state => state.devices.data;

const reducer = function(statePart = [], action = {}) {

    switch(action.type) {
        case SAVE_FETCHED_DEVICES:
            return { data:  action.payload  }
        case ADD_DEVICE:
            return { ...statePart, data: [ ...statePart.data, action.payload ] }
        case UPDATE_DEVICE:
            return { ...statePart, data: [ ...statePart.data.map((device)=>device.id===action.payload.id?action.payload:device)] }
        case REMOVE_DEVICE:
            return { ...statePart, data: [ ...statePart.data.filter((device)=>device.id!==action.payload.id)] }
                default:
            return statePart
    }
}

export default reducer


问:
How to enforce implementation of nested class properties?
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

```<code>    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }
</code>```

In TypeScript it would work like this:

```<code>
type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

</code>```

答:
If I understood your requirements, here is the solution

Declare NavMenu properties as interface

```<code>public interface NavMenuProps
{
    public string FirstMenuHeader { get; set; }
    public string SecondMenuHeader { get; set; }
    public string ThirdMenuHeader { get; set; }
}
</code>```

Declare Translation class as abstract with abstract properties

```<code>public abstract class Translation : NavMenuProps
{
    public abstract string FirstMenuHeader { get; set; }
    public abstract string SecondMenuHeader { get; set; }
    public abstract string ThirdMenuHeader { get; set; }
}
</code>```

Now you can implemented each language translation, if you do not implement NavMenuProps properties in any language class, code editor will complain like "Does not implement inherited abstract member"

```<code>public class English : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}

public class Dutch : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}

public class French : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}
</code>```

Body:
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }

In TypeScript it would work like this:

type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

Body:
If I understood your requirements, here is the solution

Declare NavMenu properties as interface

public interface NavMenuProps
{
    public string FirstMenuHeader { get; set; }
    public string SecondMenuHeader { get; set; }
    public string ThirdMenuHeader { get; set; }
}

Declare Translation class as abstract with abstract properties

public abstract class Translation : NavMenuProps
{
    public abstract string FirstMenuHeader { get; set; }
    public abstract string SecondMenuHeader { get; set; }
    public abstract string ThirdMenuHeader { get; set; }
}

Now you can implemented each language translation, if you do not implement NavMenuProps properties in any language class, code editor will complain like "Does not implement inherited abstract member"

public class English : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}

public class Dutch : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}

public class French : Translation
{
    public override string FirstMenuHeader { get; set; }
    public override string SecondMenuHeader { get; set; }
    public override string ThirdMenuHeader { get; set; }
}


问:
How to replace value in a dataframe and convert it to a list of dictionary in python pandas
I have a data frame that is created after a query is executed. Call it df1.

```<code> customerID flag
0        123   No
</code>```

Now, I have another list of dictionary like below:

```<code>list2 = [{"customerID": "123", "response": "yes", "flag": ""}]
</code>```

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

```<code>df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())
</code>```

Expected output:

```<code>[{"customerID": "123", "response": "yes", "flag": "No"}]
</code>```

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

答:
As you have a list of dictionaries, it might not be worth converting to DataFrame, performing a merge/map, etc.

Maybe just loop and mutate the object:

```<code>s = df1.set_index('customerID')['flag']

for d in list2:
    if d['customerID'] in {'123'} and d['customerID'] in s:
        d['flag'] = s[d['customerID']]
</code>```

output:

```<code>[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]
</code>```

Body:
I have a data frame that is created after a query is executed. Call it df1.

 customerID flag
0        123   No

Now, I have another list of dictionary like below:

list2 = [{"customerID": "123", "response": "yes", "flag": ""}]

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())

Expected output:

[{"customerID": "123", "response": "yes", "flag": "No"}]

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

Body:
As you have a list of dictionaries, it might not be worth converting to DataFrame, performing a merge/map, etc.

Maybe just loop and mutate the object:

s = df1.set_index('customerID')['flag']

for d in list2:
    if d['customerID'] in {'123'} and d['customerID'] in s:
        d['flag'] = s[d['customerID']]

output:

[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]