问:
How do I get the pendulums to syncrochnize in my simulation?
I'm making a simulation of pendulum motion using a simple gravity pendulum in VPython.
The relationships appear to be according to what is expected except, when I start a pendulum at a lower angle it does not have the same period as a pendulum of the same length. What could I do to fix it?</p>
```<code>from visual import *

def mark(place, hue):

    marker = sphere(pos=place,radius = 0.2, color =hue)

def pendulum(bob,rod):
    if bob.pos.x < 0:
        bob.theta =-diff_angle(bob.pos,vec(0,-1,0))
    else:
        bob.theta =diff_angle(bob.pos,vec(0,-1,0))
    rod.long = mag(rod.axis)
    bob.acceleration= -(field_strength/rod.long)*sin(bob.theta)
    bob.velocity= bob.velocity + bob.acceleration
    bob.theta = bob.theta + bob.velocity*deltat
    bob.pos= vec(rod.long*sin(bob.theta),-rod.long*cos(bob.theta),0)
    mark(bob.pos,bob.color)
    rod.axis= vec(rod.long*sin(bob.theta),-rod.long*cos(bob.theta),0)
    if bob.pos == bob.initialplace:
        print(t)

theta0=1.5
theta1=1
rod1=10
rod2=10
rod3=40
ball1 = sphere(pos= vec(rod1*sin(theta0),-rod1*cos(theta0),0), radius=1, color=color.red)
ball1.theta = diff_angle(ball1.pos,vec(0,-1,0))
string1 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod1,0), color=color.red)
ball1.velocity = 0
ball1.acceleration = 0
ball1.initialplace = ball1.pos

ball2 = sphere(pos= vec(rod2*sin(theta1),-rod2*cos(theta1),0), radius=1, color=color.white)
ball2.theta = diff_angle(ball2.pos,vec(0,-1,0))
string2 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod2,0), color=color.white)
ball2.velocity = 0
ball2.acceleration = 0
ball2.initialplace = ball2.pos

ball3 = sphere(pos= vec(rod3*sin(theta0),-rod3*cos(theta0),0), radius=1, color=color.blue)
ball3.theta = diff_angle(ball3.pos,vec(0,-1,0))
string3 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod3,0), color=color.blue)
ball3.velocity = 0
ball3.acceleration = 0
ball3.initialplace = ball3.pos

field_strength =9.81
t=0
deltat= 0.001

while t<500:
    rate(50)
    pendulum(ball1,string1)
    pendulum(ball2,string2)
    pendulum(ball3,string3)
    t = t+deltat
</code>```

答:
The period of a pendulum is independent of the maximum angle only if the angle is small (that is, if you can confound the angle with its sine). You are using quite large angles to make your comparison, and that's why you see the difference between the observed periods.

Writing equations in SO is very painful so I just refer you to this wikipedia page for more details.

Body:
I'm making a simulation of pendulum motion using a simple gravity pendulum in VPython.
The relationships appear to be according to what is expected except, when I start a pendulum at a lower angle it does not have the same period as a pendulum of the same length. What could I do to fix it?

from visual import *

def mark(place, hue):

    marker = sphere(pos=place,radius = 0.2, color =hue)

def pendulum(bob,rod):
    if bob.pos.x < 0:
        bob.theta =-diff_angle(bob.pos,vec(0,-1,0))
    else:
        bob.theta =diff_angle(bob.pos,vec(0,-1,0))
    rod.long = mag(rod.axis)
    bob.acceleration= -(field_strength/rod.long)*sin(bob.theta)
    bob.velocity= bob.velocity + bob.acceleration
    bob.theta = bob.theta + bob.velocity*deltat
    bob.pos= vec(rod.long*sin(bob.theta),-rod.long*cos(bob.theta),0)
    mark(bob.pos,bob.color)
    rod.axis= vec(rod.long*sin(bob.theta),-rod.long*cos(bob.theta),0)
    if bob.pos == bob.initialplace:
        print(t)

theta0=1.5
theta1=1
rod1=10
rod2=10
rod3=40
ball1 = sphere(pos= vec(rod1*sin(theta0),-rod1*cos(theta0),0), radius=1, color=color.red)
ball1.theta = diff_angle(ball1.pos,vec(0,-1,0))
string1 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod1,0), color=color.red)
ball1.velocity = 0
ball1.acceleration = 0
ball1.initialplace = ball1.pos

ball2 = sphere(pos= vec(rod2*sin(theta1),-rod2*cos(theta1),0), radius=1, color=color.white)
ball2.theta = diff_angle(ball2.pos,vec(0,-1,0))
string2 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod2,0), color=color.white)
ball2.velocity = 0
ball2.acceleration = 0
ball2.initialplace = ball2.pos

ball3 = sphere(pos= vec(rod3*sin(theta0),-rod3*cos(theta0),0), radius=1, color=color.blue)
ball3.theta = diff_angle(ball3.pos,vec(0,-1,0))
string3 = cylinder(pos = vec(0,0,0), radius= 0.1, axis=vec(0,-rod3,0), color=color.blue)
ball3.velocity = 0
ball3.acceleration = 0
ball3.initialplace = ball3.pos

field_strength =9.81
t=0
deltat= 0.001

while t<500:
    rate(50)
    pendulum(ball1,string1)
    pendulum(ball2,string2)
    pendulum(ball3,string3)
    t = t+deltat


来源: stackexchange

问:
List for all disable triggers
I need to make a list of all triggers which aren't running.

```<code>declare @Trigger nvarchar(150)
select @Trigger = t1.name from  sys.triggers as t1 WHERE t1.is_disabled = 1
declare @disable int
select @disable =t1.is_disabled FROM sys.triggers t1 WHERE t1.is_disabled = 0
While @disable <= 1
BEGIN
    Print 'Trigger ' + @Trigger +  ' is disable!'
    set @disable = @disable + 1
END
</code>```

As a result I have only one trigger, but there are another 10 which are disabled.

Any ideas?

答:
This should do the trick</p>
```<code>SELECT
    t2.[name] TableTriggerReference
    , SCHEMA_NAME(t2.[schema_id]) TableSchemaName
    , t3.[rowcnt] TableReferenceRowCount
    , t1.[name] TriggerName
    , 'ALTER TABLE ' + QUOTENAME(SCHEMA_NAME(t2.schema_id)) + '.' + QUOTENAME(t2.[name]) + ' ENABLE TRIGGER ' + QUOTENAME(t1.[name]) ScriptToEnableThem
FROM sys.triggers t1
    INNER JOIN sys.tables t2 ON t2.object_id = t1.parent_id
    INNER JOIN sys.sysindexes t3 On t2.object_id = t3.id
WHERE t1.is_disabled = 1
    AND t1.is_ms_shipped = 0
    AND t1.parent_class = 1
</code>```

ContentLicense: CC BY-SA 4.0

Title: List for all disable triggers

Body:
I need to make a list of all triggers which aren't running.

declare @Trigger nvarchar(150)
select @Trigger = t1.name from  sys.triggers as t1 WHERE t1.is_disabled = 1
declare @disable int
select @disable =t1.is_disabled FROM sys.triggers t1 WHERE t1.is_disabled = 0
While @disable <= 1
BEGIN
    Print 'Trigger ' + @Trigger +  ' is disable!'
    set @disable = @disable + 1
END

As a result I have only one trigger, but there are another 10 which are disabled.

Any ideas?

Body:
This should do the trick

SELECT
    t2.[name] TableTriggerReference
    , SCHEMA_NAME(t2.[schema_id]) TableSchemaName
    , t3.[rowcnt] TableReferenceRowCount
    , t1.[name] TriggerName
    , 'ALTER TABLE ' + QUOTENAME(SCHEMA_NAME(t2.schema_id)) + '.' + QUOTENAME(t2.[name]) + ' ENABLE TRIGGER ' + QUOTENAME(t1.[name]) ScriptToEnableThem
FROM sys.triggers t1
    INNER JOIN sys.tables t2 ON t2.object_id = t1.parent_id
    INNER JOIN sys.sysindexes t3 On t2.object_id = t3.id
WHERE t1.is_disabled = 1
    AND t1.is_ms_shipped = 0
    AND t1.parent_class = 1


问:
PowerShell: Restart Service By Executable Name
all

I implemented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.

I was wondering whether there is a way to restart service by executable name?

I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.

Thanks.

答:
```<code>Get-WmiObject -Class Win32_Service -Filter "PathName LIKE '%PartOfTheName%'" -ComputerName PC1 | Foreach-Object{
    $_.StopService()
    $_.StartService()
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
New Rails 7 Turbo app doesn't show the data-turbo-confirm alert messages don't fire (turbo-rails 7.1.0 and 7.1.1)
New Rails 7 app created in 2021 or 2022, when I click on a form with data-turbo-confirm, the alert message does not show.

```<code><%= form_with url: root_path(),  data: {'turbo-confirm': "Are you sure you want to submit this form?"},
               method: :delete do |f| %>
  <%= f.submit "Delete".html_safe, class: "delete-apple-button btn btn-primary btn-sm" %>
<% end %>

<br />
<%= turbo_frame_tag "apples-list"   do %>
  nothing has happened yet
<% end %>
</code>```

The HTML produced is

Page loads to:

When you click delete, no alert is shown:

Expected result:
• Alert message confirming the button action

Actual result:
• No alert is shown

答:
you can use js to do this.

the code is work for me.

function confirmDestroy(message) {
  if (!confirm(message)) {
    return false;
  }
}
```
<pre class="lang-html prettyprint-override"><code><div>
  <%= link_to "Edit this post", edit_post_path(@post) %> |
  <%= link_to "Back to posts", posts_path %>

  <%= button_to "Destroy this post", @post, method: :delete, onclick: "return confirmDestroy('Are you sure want destroy this post?')" %>
</div>
</code>```

Body:
New Rails 7 app created in 2021 or 2022, when I click on a form with data-turbo-confirm, the alert message does not show.

<%= form_with url: root_path(),  data: {'turbo-confirm': "Are you sure you want to submit this form?"},
               method: :delete do |f| %>
  <%= f.submit "Delete".html_safe, class: "delete-apple-button btn btn-primary btn-sm" %>
<% end %>

<%= turbo_frame_tag "apples-list"   do %>
  nothing has happened yet
<% end %>

The HTML produced is

Page loads to:

When you click delete, no alert is shown:

Expected result:
• Alert message confirming the button action

Actual result:
• No alert is shown

Body:
you can use js to do this.

the code is work for me.

function confirmDestroy(message) {
  if (!confirm(message)) {
    return false;
  }
}

<div>
  <%= link_to "Edit this post", edit_post_path(@post) %> |
  <%= link_to "Back to posts", posts_path %>

  <%= button_to "Destroy this post", @post, method: :delete, onclick: "return confirmDestroy('Are you sure want destroy this post?')" %>
</div>


问:
How to ignore TimeUnit.SECONDS.sleep in unit tests
I have a method which is calling sleep of 30 seconds but I dont want my unit test to have the same. I want my unit test to ignore the sleep and execute the rest on the method or reduce the sleep time to 1 sec.

```<code>public runwithSleep(){
 System.out.println("Before Sleep Time");
 TimeUnit.SECONDS.sleep(30);
 System.out.println("After Sleep Time");
}
</code>```

From the above sample code, How do I ignore the TimeUnit.SECONDS.sleep(30) when executing the unit test for this method. Basically I want to test like if i can reach this method from a condition so I dont want the sleep in the test.

答:
extract your business logic into separate method and call it after
sleep from your original method. This way in your unit test you can
just test your extracted method that does not include sleep.

Make a sleep value as a parameter instead of hardcoded value, and in your test you can set it to a small value while for regular runtime keep it to 30 sec.

Body:
I have a method which is calling sleep of 30 seconds but I dont want my unit test to have the same. I want my unit test to ignore the sleep and execute the rest on the method or reduce the sleep time to 1 sec.

public runwithSleep(){
 System.out.println("Before Sleep Time");
 TimeUnit.SECONDS.sleep(30);
 System.out.println("After Sleep Time");
}

From the above sample code, How do I ignore the TimeUnit.SECONDS.sleep(30) when executing the unit test for this method. Basically I want to test like if i can reach this method from a condition so I dont want the sleep in the test.


问:
One to one relationship doesn't work in my Spring Boot back-end
I'm developing an ecommerce backend in Spring boot. There is a 1:1 relationship between the two entities Order and Payment. At first, I create a Payment (with order field null), when the payment is succesful (suppose always in this case), I create the order related to the payment created. The problem is that the Order entity is created but it isn't connected with the Payment entity because when I try to print the order in the PaymentService it says that the order is stil null for that payment (even if, in createOrder method, I did payment.setOrder(o); as shown below). Moreover, if from the database I try to delete the payment, it tells me that the payment could not be removed because it is connected to the order, but strangely, when I try to print the order of the payment that I have created, the result is null.

OrderService:

```<code>@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) {
        System.out.println("UserId: "+userId);
        System.out.println("Payment: "+paymentId);
        System.out.println("cartId: "+cartId);
        if(userRepository.existsById(userId)){
            System.out.println("Exists");}
        User user = userRepository.findById(userId);
        if(user==null){
            System.out.println("User is null");
        }
        Payment payment = paymentRepository.findById(paymentId);
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        Order justAdded = orderRepository.save(o);
        entityManager.refresh(justAdded);
        entityManager.refresh(o);
        payment.setOrder(o);
        entityManager.refresh(payment);
        return justAdded;
    }
}
</code>```

OrderController:

```<code>@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity<Order> createOrder (@RequestParam(required = false) int paymentId,
                                                    @RequestParam(required = false) int buyerId,
                                                    @RequestParam(required = false) int cartId){

            return new ResponseEntity<>(orderService.createOrder(paymentId, buyerId, cartId), HttpStatus.OK);

    }
</code>```

PaymentService:

```<code>@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Payment addPayment(Payment p) throws PaymentAlreadyExistsException, IncorrectCardNumberException, IncorrectCvvException{//
        if(paymentRepository.existsByCardNumber(p.getCardNumber())){
            throw new PaymentAlreadyExistsException();
        }
        if(p.getCardNumber().length()!=16){
            throw new IncorrectCardNumberException();
        }
        if(p.getCvv().length()!=3)
        {
            throw new IncorrectCvvException();
        }
        System.out.println("Sto salvando il pagamento: "+p);
        Order newOrder = new Order();
        newOrder.setPayment(p);
        Order justAdded=orderRepository.save(newOrder);
        entityManager.refresh(justAdded);
        p.setOrder(justAdded);

        return paymentRepository.save(p);
    }
</code>```

PaymentController:

```<code>@RestController
@RequestMapping("/payments")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/createPayment")//funziona
    public ResponseEntity<Payment> create(@RequestBody @Valid Payment payment){
        System.out.print("Sono in paymentController.");
        try {
            Payment added=paymentService.addPayment(payment);
            return new ResponseEntity<>(added, HttpStatus.OK);
        } catch (PaymentAlreadyExistsException e) {
            return new ResponseEntity(new ResponseMessage("Payment already exists!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCardNumberException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect card number!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCvvException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect CVV"), HttpStatus.BAD_REQUEST);
        }
}
}
</code>```

Payment entity:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

}
</code>```

Order entity:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity

@Table(name = "order", schema = "purchase")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_time")
    private Date orderTime;

    @ManyToOne
    @JoinColumn(name = "buyer")
    private User buyer;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "payment_id")
    @JsonIgnore
    private Payment payment;

    @OneToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;
}
</code>```

I have the following method in PaymentService:

```<code>@Transactional(readOnly = true)//
    public List<Payment> getAllPayments(){
        List<Payment> result = paymentRepository.findAll();
        for(Payment p: result){
            if(p.getOrder()==null)
            System.out.println("Order in payment is null");
        }
        return paymentRepository.findAll();
    }
</code>```

And when I execute it (after having created a Payment, an Order and tried to connect them using the createOrder method),

Order in payment is null

is printed, so the field order for that Payment is still null.

While, the Order oject is created in the following way in the database:

I've edited createOrder method, as suggested, in the following way, but the problem persists:

```<code>@Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) throws PaymentDoesNotExistException{
        User user = userRepository.findById(userId);
        Payment payment = paymentRepository.findById(paymentId);
        if(payment == null)
        { throw new PaymentDoesNotExistException();
        }
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        payment.setOrder(o);
        orderRepository.save(o);
        return o;

    }
</code>```

答:
I saw couple of unwanted things. No need to call refresh. Just create child objects and save them first and then save the parent. Just a guidance here, make your own custom exceptions and messages.</p>
```<code>    Payment payment = paymentRepository.findById(paymentId);
    if(payment == null)
    { throw Exception("Payment not found");}
    System.out.println("Payment: "+payment);
    Cart c = cartRepository.findById(cartId);
    Order o = new Order();
    o.setPayment(payment);
    o.setCart(c);
    o.setBuyer(user);
    orderRepository.save(o);
</code>```

Body:
I'm developing an ecommerce backend in Spring boot. There is a 1:1 relationship between the two entities Order and Payment. At first, I create a Payment (with order field null), when the payment is succesful (suppose always in this case), I create the order related to the payment created. The problem is that the Order entity is created but it isn't connected with the Payment entity because when I try to print the order in the PaymentService it says that the order is stil null for that payment (even if, in createOrder method, I did payment.setOrder(o); as shown below). Moreover, if from the database I try to delete the payment, it tells me that the payment could not be removed because it is connected to the order, but strangely, when I try to print the order of the payment that I have created, the result is null.

OrderService:

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) {
        System.out.println("UserId: "+userId);
        System.out.println("Payment: "+paymentId);
        System.out.println("cartId: "+cartId);
        if(userRepository.existsById(userId)){
            System.out.println("Exists");}
        User user = userRepository.findById(userId);
        if(user==null){
            System.out.println("User is null");
        }
        Payment payment = paymentRepository.findById(paymentId);
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        Order justAdded = orderRepository.save(o);
        entityManager.refresh(justAdded);
        entityManager.refresh(o);
        payment.setOrder(o);
        entityManager.refresh(payment);
        return justAdded;
    }
}

OrderController:

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity<Order> createOrder (@RequestParam(required = false) int paymentId,
                                                    @RequestParam(required = false) int buyerId,
                                                    @RequestParam(required = false) int cartId){

            return new ResponseEntity<>(orderService.createOrder(paymentId, buyerId, cartId), HttpStatus.OK);

    }

PaymentService:

@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Payment addPayment(Payment p) throws PaymentAlreadyExistsException, IncorrectCardNumberException, IncorrectCvvException{//
        if(paymentRepository.existsByCardNumber(p.getCardNumber())){
            throw new PaymentAlreadyExistsException();
        }
        if(p.getCardNumber().length()!=16){
            throw new IncorrectCardNumberException();
        }
        if(p.getCvv().length()!=3)
        {
            throw new IncorrectCvvException();
        }
        System.out.println("Sto salvando il pagamento: "+p);
        Order newOrder = new Order();
        newOrder.setPayment(p);
        Order justAdded=orderRepository.save(newOrder);
        entityManager.refresh(justAdded);
        p.setOrder(justAdded);

        return paymentRepository.save(p);
    }

PaymentController:

@RestController
@RequestMapping("/payments")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/createPayment")//funziona
    public ResponseEntity<Payment> create(@RequestBody @Valid Payment payment){
        System.out.print("Sono in paymentController.");
        try {
            Payment added=paymentService.addPayment(payment);
            return new ResponseEntity<>(added, HttpStatus.OK);
        } catch (PaymentAlreadyExistsException e) {
            return new ResponseEntity(new ResponseMessage("Payment already exists!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCardNumberException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect card number!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCvvException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect CVV"), HttpStatus.BAD_REQUEST);
        }
}
}

Payment entity:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

}

Order entity:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity

@Table(name = "order", schema = "purchase")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_time")
    private Date orderTime;

    @ManyToOne
    @JoinColumn(name = "buyer")
    private User buyer;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "payment_id")
    @JsonIgnore
    private Payment payment;

    @OneToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;
}

I have the following method in PaymentService:

@Transactional(readOnly = true)//
    public List<Payment> getAllPayments(){
        List<Payment> result = paymentRepository.findAll();
        for(Payment p: result){
            if(p.getOrder()==null)
            System.out.println("Order in payment is null");
        }
        return paymentRepository.findAll();
    }

And when I execute it (after having created a Payment, an Order and tried to connect them using the createOrder method),

Order in payment is null

is printed, so the field order for that Payment is still null.

While, the Order oject is created in the following way in the database:

I've edited createOrder method, as suggested, in the following way, but the problem persists:

@Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) throws PaymentDoesNotExistException{
        User user = userRepository.findById(userId);
        Payment payment = paymentRepository.findById(paymentId);
        if(payment == null)
        { throw new PaymentDoesNotExistException();
        }
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        payment.setOrder(o);
        orderRepository.save(o);
        return o;

    }

Body:
I saw couple of unwanted things. No need to call refresh. Just create child objects and save them first and then save the parent. Just a guidance here, make your own custom exceptions and messages.

    Payment payment = paymentRepository.findById(paymentId);
    if(payment == null)
    { throw Exception("Payment not found");}
    System.out.println("Payment: "+payment);
    Cart c = cartRepository.findById(cartId);
    Order o = new Order();
    o.setPayment(payment);
    o.setCart(c);
    o.setBuyer(user);
    orderRepository.save(o);


问:
How does 'type DoNotCompare [0]func()' prevent comparability in Golang
Per protobuf pragma

```<code>`type DoNotCompare [0]func()`
DoNotCompare can be embedded in a struct to prevent comparability
</code>```

I am confused why DoNotCompare could prevent comparability, and try to understand with the following codes. Unfortunately, I am failed. The NonCompare struct seems could be comparability.

type DoNotCompare [0]func()

type NonCompare struct {
    DoNotCompare

    ii int8
}

type Comparer interface {
    Compare(b NonCompare) int
}

func (a NonCompare) Compare(b NonCompare) int {
    if a.ii > b.ii {
        return 1
    }
    return 0
}

func main() {
    var nc1 = NonCompare{ii: 3}
    var nc2 = NonCompare{ii: 5}

    nc1.Compare(nc2)
```

Is there anything am I missing?

答:
The prevention works on the builtin == operator, not on what your Compare() method does. Of course it can do whatever you want it to.

But if you try to use ==:

```<code>fmt.Println(nc1 == nc2)
</code>```

You get a compile-time error:

```<code>./prog.go:30:18: invalid operation: nc1 == nc2 (struct containing DoNotCompare cannot be compared)
</code>```

The reason is because values of func() type (or any function type) are not comparable, so [0]func() values are also not comparable. And structs having a field of a non-comparable type are also not comparable. Rules are listed at Spec: Comparison operators:

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:

[...]

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

[...] Slice, map, and function values are not comparable.

An array of size 0 is used so the field's size will be 0, not adding anything extra to the struct it is used in. Please note this is only guaranteed if you place 0-size fields to the first place. For details see Struct has different size if the field order is different.

Body:
Per protobuf pragma

`type DoNotCompare [0]func()`
DoNotCompare can be embedded in a struct to prevent comparability

I am confused why DoNotCompare could prevent comparability, and try to understand with the following codes. Unfortunately, I am failed. The NonCompare struct seems could be comparability.

type DoNotCompare [0]func()

type NonCompare struct {
    DoNotCompare

    ii int8
}

type Comparer interface {
    Compare(b NonCompare) int
}

func (a NonCompare) Compare(b NonCompare) int {
    if a.ii > b.ii {
        return 1
    }
    return 0
}

func main() {
    var nc1 = NonCompare{ii: 3}
    var nc2 = NonCompare{ii: 5}

    nc1.Compare(nc2)

Is there anything am I missing?

Body:
The prevention works on the builtin == operator, not on what your Compare() method does. Of course it can do whatever you want it to.

But if you try to use ==:

fmt.Println(nc1 == nc2)

You get a compile-time error:

./prog.go:30:18: invalid operation: nc1 == nc2 (struct containing DoNotCompare cannot be compared)

The reason is because values of func() type (or any function type) are not comparable, so [0]func() values are also not comparable. And structs having a field of a non-comparable type are also not comparable. Rules are listed at Spec: Comparison operators:

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:

[...]

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

[...] Slice, map, and function values are not comparable.

An array of size 0 is used so the field's size will be 0, not adding anything extra to the struct it is used in. Please note this is only guaranteed if you place 0-size fields to the first place. For details see Struct has different size if the field order is different.


问:
Oracle SQL Count orders by customers in the last 10 days based on order id
In Oracle SQL my goal is to receive the total number of orders made by a customer in the last 10 days but shown by the order id and not the customer id.

The following situation is given:

My desired outcome is:

How can I facilitate this in the most efficient way?

答:
You can try to use self-join with date of subtraction condition, the condition need to judge what rows are during 10 days

Query 1:

```<code>SELECT t1.Customer_ID,
       t1.Order_NR,
       COUNT(*) Number_Orders
FROM T t1
INNER JOIN T t2
ON t1.Customer_ID = t2.Customer_ID AND t2.Order_Date BETWEEN t1.Order_Date - 10 AND t1.Order_Date
GROUP BY t1.Customer_ID,
       t1.Order_NR
ORDER BY t1.Order_NR
</code>```

Results:

```<code>| CUSTOMER_ID | ORDER_NR | NUMBER_ORDERS |
|-------------|----------|---------------|
|         100 |        1 |             1 |
|         200 |        2 |             1 |
|         300 |        3 |             1 |
|         100 |        4 |             2 |
|         100 |        5 |             2 |
|         200 |        6 |             1 |
|         700 |        7 |             1 |
|         800 |        8 |             2 |
|         800 |        9 |             2 |
|         800 |       10 |             3 |
</code>```

Body:
You can try to use self-join with date of subtraction condition, the condition need to judge what rows are during 10 days

Query 1:

SELECT t1.Customer_ID,
       t1.Order_NR,
       COUNT(*) Number_Orders
FROM T t1
INNER JOIN T t2
ON t1.Customer_ID = t2.Customer_ID AND t2.Order_Date BETWEEN t1.Order_Date - 10 AND t1.Order_Date
GROUP BY t1.Customer_ID,
       t1.Order_NR
ORDER BY t1.Order_NR

Results:

| CUSTOMER_ID | ORDER_NR | NUMBER_ORDERS |
|-------------|----------|---------------|
|         100 |        1 |             1 |
|         200 |        2 |             1 |
|         300 |        3 |             1 |
|         100 |        4 |             2 |
|         100 |        5 |             2 |
|         200 |        6 |             1 |
|         700 |        7 |             1 |
|         800 |        8 |             2 |
|         800 |        9 |             2 |
|         800 |       10 |             3 |


问:
How to do a SQL GROUP BY on multiple dimensions in Tableau?
I am able to do SQL GROUP BY x in Tableau by right clicking the dimension x and then clicking Create Group. How do I do GROUP BY x, y where x and y are two separate dimensions or columns?

答:
You can just simply drag and drop x and y pills in the column/row area and then drag and drop your measure in the marks area. In this way, your measure(s) will be grouped by x and y.
If you click on the measure in the marks area you can select the aggregation function.

Look at this: Data Aggregation in Tableau


问:
C++ check if entered value is unsigned integer
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

```<code>#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}
</code>```

How to do that ?

答:
When you input a string value, operator>> tries to extract your string input into variable 'number'. This fails since string cannot be converted into unsigned int. This wrong input value is then left in the buffer, while std::cin fails. Any future inputs for extraction will also fail silently. To get past this use,

```<code>#include <limits>
if (std::cin.fail()) // has input extraction failed?
{
    std::cin.clear(); // then clear cin and reset it
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //clear buffer
}
</code>```

std::cin.ignore() takes in two parameters - the first one is number of characters to remove and the second is the parameter until which to remove characters from the buffer.

std::numeric_limits<std::streamsize>::max() just gives the largest value that can be stored in type std::streamsize. You can just use a value like 200 or 300, but if the user has somehow input more values, using std::numeric_limits would help guard against this possibility. Add this check in the appropriate place in your code.

Body:
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}

How to do that ?

Body:
When you input a string value, operator>> tries to extract your string input into variable 'number'. This fails since string cannot be converted into unsigned int. This wrong input value is then left in the buffer, while std::cin fails. Any future inputs for extraction will also fail silently. To get past this use,

#include <limits>
if (std::cin.fail()) // has input extraction failed?
{
    std::cin.clear(); // then clear cin and reset it
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //clear buffer
}

std::cin.ignore() takes in two parameters - the first one is number of characters to remove and the second is the parameter until which to remove characters from the buffer.

std::numeric_limits<std::streamsize>::max() just gives the largest value that can be stored in type std::streamsize. You can just use a value like 200 or 300, but if the user has somehow input more values, using std::numeric_limits would help guard against this possibility. Add this check in the appropriate place in your code.


问:
Some material icon doesn't show in production
I don't know why but only in production some material icon doesn't appear, as you can see from the image the first icon is missing:

here's the code:

```<code> <mat-nav-list>
   <a mat-list-item routerLink="/dashboard" matTooltip="dashboard">
     <mat-icon matListIcon>bar_chart</mat-icon>
   </a>
   <a mat-list-item (click)="routeToContacts()" matTooltip="contacts">
     <mat-icon matListIcon>people</mat-icon>
   </a>
</code>```

答: Had a similar issue, the icon event_repeat appearad as two wrong icons in production build but worked in development build. The build process changes how fonts are embedded. In my case an old version of the woff2-file was loaded (v109 instead of the current v121). The appropriate css in the folder node_modules\.cache\angular-build-fonts, so I deleted node_modules and ran cmp ci. That fixed this issue.

Body:
I don't know why but only in production some material icon doesn't appear, as you can see from the image the first icon is missing:

here's the code:

 <mat-nav-list>

     <mat-icon matListIcon>bar_chart</mat-icon>

     <mat-icon matListIcon>people</mat-icon>


问:
Increment a counter inside a byte array
I have an array of 5 bytes (fixed length). First 21 bits represent a counter and the rest 19 some id. I need to increment the counter by one. How do I do that?</p>

答:
I'm not sure I solved your problem. Since the memory layout is not described in detail, I assumed a layout. You can obtain the counter, increase it by 1, and then set the counter. If the layout is as desired, it needs to be fully tested. I'm not dealing with data overflow situations, and you may need to add some restrictions.</p>
```<code>public class Test {
    public static void main(String[] args) {
        byte[] bytes = new byte[5];
        bytes[2] = 5;
        for (int i = 0; i <= 0x1fffff; i++) {
            setCount(bytes, i);
            if (getCount(bytes) != i) {
                System.out.println(i);
                debug(bytes);
            }
        }
    }

    public static int getCount(byte[] bytes) {
        return ((bytes[2] >> 3) & 0x1f) + ((bytes[1] << 5) & 0x1fff) + ((bytes[0] << 13) & 0x1fffff);
    }

    public static void setCount(byte[] bytes, int count) {
        bytes[0] = (byte) (count >> 13 & 0xff);
        bytes[1] = (byte) (count >> 5 & 0xff);
        bytes[2] = (byte) ((bytes[2] & 0x7) + ((count & 0x1f) << 3));
    }

    public static void debug(byte[] bytes) {
        for (byte b : bytes) {
            for (int i = 7; i >= 0; i--) {
                System.out.print(b >> i & 1);
            }
            System.out.print(" ");
        }
        System.out.println();
        System.out.println("Count:" + getCount(bytes));
    }

    public static void printInt(int num) {
        for (int i = 31; i >= 0; i--) {
            System.out.print(num >> i & 1);
        }
        System.out.println();
    }
}
</code>```

Title: Increment a counter inside a byte array

Body:
I'm not sure I solved your problem. Since the memory layout is not described in detail, I assumed a layout. You can obtain the counter, increase it by 1, and then set the counter. If the layout is as desired, it needs to be fully tested. I'm not dealing with data overflow situations, and you may need to add some restrictions.

public class Test {
    public static void main(String[] args) {
        byte[] bytes = new byte[5];
        bytes[2] = 5;
        for (int i = 0; i <= 0x1fffff; i++) {
            setCount(bytes, i);
            if (getCount(bytes) != i) {
                System.out.println(i);
                debug(bytes);
            }
        }
    }

    public static int getCount(byte[] bytes) {
        return ((bytes[2] >> 3) & 0x1f) + ((bytes[1] << 5) & 0x1fff) + ((bytes[0] << 13) & 0x1fffff);
    }

    public static void setCount(byte[] bytes, int count) {
        bytes[0] = (byte) (count >> 13 & 0xff);
        bytes[1] = (byte) (count >> 5 & 0xff);
        bytes[2] = (byte) ((bytes[2] & 0x7) + ((count & 0x1f) << 3));
    }

    public static void debug(byte[] bytes) {
        for (byte b : bytes) {
            for (int i = 7; i >= 0; i--) {
                System.out.print(b >> i & 1);
            }
            System.out.print(" ");
        }
        System.out.println();
        System.out.println("Count:" + getCount(bytes));
    }

    public static void printInt(int num) {
        for (int i = 31; i >= 0; i--) {
            System.out.print(num >> i & 1);
        }
        System.out.println();
    }
}


问:
Webpack Module Federation handling when the remote app is down/unavailable
I am currently exploring about micro frontend with Module Federation. I just forked a sandbox, tried it with success when the both modules available. It has 2 modules, app1 as the host, and app2 as the remote component. But as I think that each modules in module federation should be independent, I tried to make the app2 unavailable as I didn't start it. Therefore I got error when I run the app1, it finished loading with displaying the fallback of the React's Suspense, but milliseconds later, it becomes blank as there's error I can't retrieve thus I don't really know.

After that, I tried Webpack's Promise Based Dynamic Remotes, then my webpack-config.js becomes like this:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require('webpack').container;
const ExternalTemplateRemotesPlugin = require('external-remotes-plugin');
const path = require('path');

module.exports = {
  entry: './src/index',
  mode: 'development',
  devServer: {
    static: path.join(__dirname, 'dist'),
    port: 3001,
  },
  output: {
    publicPath: 'auto',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['@babel/preset-react'],
        },
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'app1',
      remotes: {
        app2: Promise((resolve) => {
          const urlParams = new URLSearchParams(window.location.search);
          const version = urlParams.get('app1VersionParam');
          // This part depends on how you plan on hosting and versioning your federated modules
          const remoteUrlWithVersion = '[app2Url]' + '/remoteEntry.js';
          const script = document.createElement('script');
          script.src = remoteUrlWithVersion;
          script.onload = () => {
            // the injected script has loaded and is available on window
            // we can now resolve this Promise
            const proxy = {
              get: (request) => window.app1.get(request),
              init: (arg) => {
                try {
                  return window.app1.init(arg);
                } catch (e) {
                  console.log('remote container already initialized');
                }
              },
            };
            resolve(proxy);
          };
          // inject this script with the src set to the versioned remoteEntry.js
          document.head.appendChild(script);
        }),
        // "app2@[app2Url]/remoteEntry.js",
      },
      shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
    }),
    new ExternalTemplateRemotesPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
  ],
};

```
<p>I tried start the <code>app1</code> again, then this error comes:</p>
```$ webpack serve
[webpack-cli] Failed to load '/home/projects/github-rl5uyr/app1/webpack.config.js' config
[webpack-cli] TypeError: undefined is not a promise
    at Promise (<anonymous>)
    at Object.eval (/home/projects/github-rl5uyr/app1/webpack.config.js:32:15)
    at Object.function (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:11:114831)
    at Module._compile (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:167880)
    at Object.Module._extensions..js (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:168239)
    at Module.load (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:166317)
    at Function.Module._load (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:163857)
    at Module.require (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:166635)
    at i (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:427483)
    at _0x5301a6 (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:11:114450)
```

So, can the module federations run independently each other? If not, what's the real difference as normal library dependencies of monolith front end instead of this sophisticated micro frontend, that I assumed it should be able to work independently like microservices?

答:
I think there are some stuff to be fixed in that promise definition:
first of all it should be defined as a string

app2: new Promise((resolve) => { ....
Where the configuration passed for app2 is a string between ` character

As stated in the docs

After that you should change your proxy definition to fetch window.app2 not window.app1.

Finally remoteUrlWithVersion = '[app2Url]' + '/remoteEntry.js'; is not a valid URL

Hope it helps

Body:
I am currently exploring about micro frontend with Module Federation. I just forked a sandbox, tried it with success when the both modules available. It has 2 modules, app1 as the host, and app2 as the remote component. But as I think that each modules in module federation should be independent, I tried to make the app2 unavailable as I didn't start it. Therefore I got error when I run the app1, it finished loading with displaying the fallback of the React's Suspense, but milliseconds later, it becomes blank as there's error I can't retrieve thus I don't really know.

After that, I tried Webpack's Promise Based Dynamic Remotes, then my webpack-config.js becomes like this:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require('webpack').container;
const ExternalTemplateRemotesPlugin = require('external-remotes-plugin');
const path = require('path');

module.exports = {
  entry: './src/index',
  mode: 'development',
  devServer: {
    static: path.join(__dirname, 'dist'),
    port: 3001,
  },
  output: {
    publicPath: 'auto',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['@babel/preset-react'],
        },
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'app1',
      remotes: {
        app2: Promise((resolve) => {
          const urlParams = new URLSearchParams(window.location.search);
          const version = urlParams.get('app1VersionParam');
          // This part depends on how you plan on hosting and versioning your federated modules
          const remoteUrlWithVersion = '[app2Url]' + '/remoteEntry.js';
          const script = document.createElement('script');
          script.src = remoteUrlWithVersion;
          script.onload = () => {
            // the injected script has loaded and is available on window
            // we can now resolve this Promise
            const proxy = {
              get: (request) => window.app1.get(request),
              init: (arg) => {
                try {
                  return window.app1.init(arg);
                } catch (e) {
                  console.log('remote container already initialized');
                }
              },
            };
            resolve(proxy);
          };
          // inject this script with the src set to the versioned remoteEntry.js
          document.head.appendChild(script);
        }),
        // "app2@[app2Url]/remoteEntry.js",
      },
      shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
    }),
    new ExternalTemplateRemotesPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
  ],
};

I tried start the app1 again, then this error comes:

$ webpack serve
[webpack-cli] Failed to load '/home/projects/github-rl5uyr/app1/webpack.config.js' config
[webpack-cli] TypeError: undefined is not a promise
    at Promise (<anonymous>)
    at Object.eval (/home/projects/github-rl5uyr/app1/webpack.config.js:32:15)
    at Object.function (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:11:114831)
    at Module._compile (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:167880)
    at Object.Module._extensions..js (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:168239)
    at Module.load (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:166317)
    at Function.Module._load (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:163857)
    at Module.require (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:166635)
    at i (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:6:427483)
    at _0x5301a6 (https://github-rl5uyr.w.staticblitz.com/blitz.01faa899fac41642342f4b7113feacabea334fa1.js:11:114450)

So, can the module federations run independently each other? If not, what's the real difference as normal library dependencies of monolith front end instead of this sophisticated micro frontend, that I assumed it should be able to work independently like microservices?


问:
Skipping errors in a loop? (PHP)
I have a loop where the code loops and in every loop it connects to different server and then makes MySQL query. However sometimes one of the loops/queries cannot reach to the end and all the code breaks. Is there a way where if the loop gives error then skip the processes / move to next loop?</p>

答: Inside that loop ,check the connection and if it is made, do the logic. So that if connection is not made, the logic part would be skipped.</p>

Title: Skipping errors in a loop? (PHP)


问:
How to convert two dimensional array of string into one of type int?
How can I convert a double array of type String to a double array of type int ?

```<code>    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }
</code>```

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

```<code>int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}
</code>```

but it give me

```<code>4
4
5
2
9
2
...
</code>```

Best Regards!

答:
You could parse it manually, as done in other answers, but since you are using spring, you should use the tools it offers you.

Spring uses jackson's ObjectMapper for serialization and deserialization by default. A bean of this type is preconfigured for you, you can autowire it in your controller method and use it. Then the entire parsing is this:

```<code>int[][] parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);
</code>```

And your controller method looks like this:

```<code>@PostMapping("/hole/coordinate")
@ResponseBody
public String saveCoordinate(@RequestBody Map<String, Object> params, ObjectMapper objectMapper) {
    System.out.println("params = " + params);
    System.out.println("params = " + params.get("coordinate"));
    //get string from your params
    String coordinates = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
    int[][] parsedCoordinates;
    try {
        parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);
    } catch (JsonProcessingException exc) {
        //that's a bad way to handle error, but it's an example
        //you might return error message like - invalid coordinate format
        //or whatever you need
        exc.printStackTrace();
        throw new RuntimeException(exc);
    }
    //printing parsed result to check it
    for (int i = 0; i < parsedCoordinates.length; i++) {
        int[] inner = parsedCoordinates[i];
        for (int j = 0; j < inner.length; j++) {
            System.out.printf("pos %d-%d, value %d%n", i, j, parsedCoordinates[i][j]);
        }
    }
    return "success";
}
</code>```

Body:
How can I convert a double array of type String to a double array of type int ?

    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}

but it give me

4
4
5
2
9
2
...

Best Regards!

Body:
You could parse it manually, as done in other answers, but since you are using spring, you should use the tools it offers you.

Spring uses jackson's ObjectMapper for serialization and deserialization by default. A bean of this type is preconfigured for you, you can autowire it in your controller method and use it. Then the entire parsing is this:

int[][] parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);

And your controller method looks like this:

@PostMapping("/hole/coordinate")
@ResponseBody
public String saveCoordinate(@RequestBody Map<String, Object> params, ObjectMapper objectMapper) {
    System.out.println("params = " + params);
    System.out.println("params = " + params.get("coordinate"));
    //get string from your params
    String coordinates = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
    int[][] parsedCoordinates;
    try {
        parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);
    } catch (JsonProcessingException exc) {
        //that's a bad way to handle error, but it's an example
        //you might return error message like - invalid coordinate format
        //or whatever you need
        exc.printStackTrace();
        throw new RuntimeException(exc);
    }
    //printing parsed result to check it
    for (int i = 0; i < parsedCoordinates.length; i++) {
        int[] inner = parsedCoordinates[i];
        for (int j = 0; j < inner.length; j++) {
            System.out.printf("pos %d-%d, value %d%n", i, j, parsedCoordinates[i][j]);
        }
    }
    return "success";
}


问:
POST: register return The GET method is not supported for this route. Supported methods: POST in laravel-api 8
After I deployed my project to server the Route: register start return this:

```<code>"message": "The GET method is not supported for this route. Supported methods: POST.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
</code>```

in localhost, it worked Succesful !!!

My route list is:

| POST| api/register | App\Http\Controllers\Auth\UserAuthController@register

My route in api.php:

```<code>Route::post('register', [UserAuthController::class, 'register']);
</code>```

Controller:

```<code>class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed',
            'phone_number' => 'required|numeric|unique:users,phone_number',
            'country' => 'required|string',
            'city' => 'required|string',
            'address' => 'string',
            'VIP' => 'boolean'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response(['user' => $user, 'token' => $token], 201);
    }
</code>```

答:
use the following commands:

```<code>php artisan cache:clear
php artisan route:cache
php artisan view:clear
composer dump-autoload
</code>```

update:

if it doesn't work check if the url the same {url}/api/register

Body:
After I deployed my project to server the Route: register start return this:

"message": "The GET method is not supported for this route. Supported methods: POST.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",

in localhost, it worked Succesful !!!

My route list is:

| POST| api/register | App\Http\Controllers\Auth\UserAuthController@register

My route in api.php:

Route::post('register', [UserAuthController::class, 'register']);

Controller:

class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed',
            'phone_number' => 'required|numeric|unique:users,phone_number',
            'country' => 'required|string',
            'city' => 'required|string',
            'address' => 'string',
            'VIP' => 'boolean'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response(['user' => $user, 'token' => $token], 201);
    }

Body:
use the following commands:

php artisan cache:clear
php artisan route:cache
php artisan view:clear
composer dump-autoload

update:

if it doesn't work check if the url the same {url}/api/register


问:
Selecting a div in jQuery & appending to the DOM
```<code>        var activeMsg=[];       // Active Users
        var noactiveMsg=[];     // Non-Active Users with a Pending Message
        var noactiveNomsg=[];       // Non-Active Users without a Pending Message

        $('div.chatmember').each(function() {
            currentMember=$(this);

            if($(this).children().children('div').hasClass('chatactivestatus_online')) {
                alert('online');
                activeMsg.push(currentMember);
            }
            if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
                alert('offline');
                noactiveMsg.push(currentMember);
            }
        });

        $.each(noactiveMsg, function(i, e){
             $('#chatCenterMembers').append(e.html());
         })
</code>```

The above code is quering DOM structure that looks like this:

```<code> <div id="chatCenterMembers">
   <div class="chatmember">
      <a class="ststusTitle">
         <div class="chatactivestatus_online"></div>
</code>```

it all works except for currentMember=$(this);
I believe this should hold

when I do the append at the end of the code above it doesn't add
 back into the dom. It adds its children elements only.

答:
I think you just raced ahead a little bit. Using your js, $(this) will refer to your inner div. $(this).parent() will refer to the outer one.

some html

```<code><div id="chatCenterMembers">
   <div id="adam" class="chatmember">
       hello!
    </div>
</div>
</code>```

the js

```<code>$(function(){
    $("div.chatmember").each(function(){

        // current member is now div#adam
        var currentMember = $(this);

        currentMember.css('border', '5px solid blue');

        // parent of currentMember references div#chatCenterMembers
        currentMember.parent().css('border', '5px solid red');

    });
});
</code>```

see it working here on jsFiddle

Body:
        var activeMsg=[];       // Active Users
        var noactiveMsg=[];     // Non-Active Users with a Pending Message
        var noactiveNomsg=[];       // Non-Active Users without a Pending Message

        $('div.chatmember').each(function() {
            currentMember=$(this);

            if($(this).children().children('div').hasClass('chatactivestatus_online')) {
                alert('online');
                activeMsg.push(currentMember);
            }
            if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
                alert('offline');
                noactiveMsg.push(currentMember);
            }
        });

        $.each(noactiveMsg, function(i, e){
             $('#chatCenterMembers').append(e.html());
         })

The above code is quering DOM structure that looks like this:

it all works except for currentMember=$(this);
I believe this should hold

when I do the append at the end of the code above it doesn't add
 back into the dom. It adds its children elements only.

Body:
I think you just raced ahead a little bit. Using your js, $(this) will refer to your inner div. $(this).parent() will refer to the outer one.

some html

<div id="chatCenterMembers">
   <div id="adam" class="chatmember">
       hello!
    </div>
</div>

the js

$(function(){
    $("div.chatmember").each(function(){

        // current member is now div#adam
        var currentMember = $(this);

        currentMember.css('border', '5px solid blue');

        // parent of currentMember references div#chatCenterMembers
        currentMember.parent().css('border', '5px solid red');

    });
});

see it working here on jsFiddle


问:
Problem with adding or deleting the resource roles in the access package in Azure
I'm new to Azure AD. However, I observed a weired behaviour in Azure.

After adding / deleting the resource group. The notification says, its success. However, after checking again in few minutes:- (The deleted resources roles are added back into package and the added resources are getting removed as well. This is happening automatically.) I do't have any clue, Anyone faced similar issues? OR, could it be some seetings which is forcing group( sg-ag-rg* group) to stay intact to the access package?

Could anyone please clarify or give some clue? Thanks.

答:
•   It might be because they are getting deleted in background and when you check again instantaneously, you would be seeing them as being there itself again. Or else, it might be due to an Azure policy assignment to specific selected users due to which, even after deleting the resource group, the access package assigned to the user is not deleted and is recreated once again since it is a part of Azure AD Identity and Governance.

•   I would suggest you to please remove all access package assignments for all the users, groups and applications or sites and their entitlements and then try deleting the access packages and subsequently, the resource group. Thus, in this way, the resource role related to access package will be deleted successfully and will not be recreated even after resource group deletion.

For more information regarding this, you can please refer to the documentation link below: -

https://learn.microsoft.com/en-us/azure/active-directory/governance/entitlement-management-access-package-resources#remove-resource-roles

https://learn.microsoft.com/en-us/azure/active-directory/governance/entitlement-management-access-package-edit#delete-an-access-package


问:
Performance cost of accessing memory using calculated adresses (base + offset) vs register
Is there any performance cost of accessing data by a calculted address like vmovupd ymm13, YMMWORD PTR [rbp+r14*8+78D0h] versus using an adress stored in a register like

vmovapd ymm13, YMMWORD PTR [rdi]

or
vmovupd ymm0,ymmword ptr [r9] vs
vmovupd ymm0,ymmword ptr [r9+60h]

More precisely: Does the arithmetic in [rbp+r14*8+78D0h] or [r9+60h] cost something and if so, what is the background?

Imagine a loop having a counter that serves as base offset per iteration for accessing various blocks of memory like this example in c.

```<code>for (uint64_t i = 0; i < n; i++)
{
    doSomethingWith (&data0[i],&otherData[i]);
    doSomethingDifferentWith (&data1[i+4],&otherData1[i+8]);
    doSomethingElseWith (&data2[i+8],&otherData2[i+4]);
}
</code>```

This example produces that kind of offset like adressed.
I wonder if it might be beneficial to iterate using stored adresses instead, which comes with the cost of extra instructions produced by pData0++; pOtherdata += 4; pData2 +=8; ... like lea, add, etc.

This is not about how to visualize effects using profilers.
My aim is to understand the theory and mechanisms under the hood.

答:
The specifics depend on the microarchitecture of the processor you are programming for.  Generally speaking, there is a penalty for using a SIB operand if all fields in the operand are filled in, i.e. if there is a base, an index, and a displacement.  The penalty is 1 µop extra latency for computing the address.

Refer to Agner Fog's microarchitecture guide for a more detailed explanation.

Body:
Is there any performance cost of accessing data by a calculted address like vmovupd ymm13, YMMWORD PTR [rbp+r14*8+78D0h] versus using an adress stored in a register like

vmovapd ymm13, YMMWORD PTR [rdi]

or
vmovupd ymm0,ymmword ptr [r9] vs
vmovupd ymm0,ymmword ptr [r9+60h]

More precisely: Does the arithmetic in [rbp+r14*8+78D0h] or [r9+60h] cost something and if so, what is the background?

Imagine a loop having a counter that serves as base offset per iteration for accessing various blocks of memory like this example in c.

for (uint64_t i = 0; i < n; i++)
{
    doSomethingWith (&data0[i],&otherData[i]);
    doSomethingDifferentWith (&data1[i+4],&otherData1[i+8]);
    doSomethingElseWith (&data2[i+8],&otherData2[i+4]);
}

This example produces that kind of offset like adressed.
I wonder if it might be beneficial to iterate using stored adresses instead, which comes with the cost of extra instructions produced by pData0++; pOtherdata += 4; pData2 +=8; ... like lea, add, etc.

This is not about how to visualize effects using profilers.
My aim is to understand the theory and mechanisms under the hood.


问:
Mirror repository from BitBucket Cloud to Google Cloud Repository for App Password changes
with the upcoming changes as outlined in

https://bitbucket.org/blog/deprecating-atlassian-account-password-for-git-and-bitbucket-api-activity

How does it affect mirroring a Bitbucket Repository to Google Cloud Repository? I noticed that in the instructions in Google https://cloud.google.com/source-repositories/docs/mirroring-a-bitbucket-repository , the credentials used during logging in to Bitbucket are the account email and password, not the username and app password.

Does anyone have an idea whether things will break and what changes are required to get mirroring working?

答:
According to Atlassian this change will only affect channels that are utilizing account password:

Bitbucket users will no longer be able to use their Atlassian account password to interact with Bitbucket via Git over https and the Bitbucket API

App passwords are currently not working when mirroring Bitbucket in GCP. You can either contact their support or wait for them to contact you:

We'll be contacting teams and users based on what we find in our logs for Atlassian account password usage.


问:
Show Spinning Animation while Page Loads ASP.NET
I want to know that in my web application, the user clicks to the menu, It's buffering sometimes to load the page.

So the Theme I used to create the system has inbuild animation for that. How I can trigger this when loading until the page completely loads to view.

This is the animation

```<code> <div id="loading" class="overlay"><i class="fas fa-2x fa-sync-alt fa-spin"></i></div>
</code>```

This is currently how I placed it on the page.

```<code><div class="card">
  <div class="card-header">
    <h3 class="card-title">
      <b>Company List</b>
    </h3>
  </div>
  <div id="loading" class="overlay">
    <i class="fas fa-2x fa-sync-alt fa-spin"></i>
  </div>
  <!-- /.card-header -->
  <div class="card-body p-0">
    <table class="table table-striped">
      <tr>
        <th> Company Name </th>
        <th> @Html.DisplayNameFor(model => model.Status) </th>
        <th></th>
      </tr>
      <tbody> @foreach (var item in Model) { <tr>
          <td> @Html.DisplayFor(modelItem => item.CompanyName) </td>
          <td> @Html.DisplayFor(modelItem => item.Status) </td>
          <td> @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn btn-warning pull-right" }) @Html.ActionLink("View", "Details", new { id = item.Id }, new { @class = "btn btn-success pull-right" }) @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn btn-danger pull-right" }) </td>
        </tr> } </tbody>
    </table>
  </div>
  <!-- /.card-body -->
</div>

</code>```

I Used this JQuery

```<code><script>
    $(window).load(function () {
        $('#loading').hide();
    });
</script>
</code>```

答:
$(window).load() has been removed in jQuery 3.0. Try using:

```<code>$(window).on('load', function () {
    $('#loading').hide();
});
</code>```

Body:
I want to know that in my web application, the user clicks to the menu, It's buffering sometimes to load the page.

So the Theme I used to create the system has inbuild animation for that. How I can trigger this when loading until the page completely loads to view.

This is the animation

This is currently how I placed it on the page.

      Company List

         Company Name
         @Html.DisplayNameFor(model => model.Status)

 @foreach (var item in Model) {

           @Html.DisplayFor(modelItem => item.CompanyName)
           @Html.DisplayFor(modelItem => item.Status)
           @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn btn-warning pull-right" }) @Html.ActionLink("View", "Details", new { id = item.Id }, new { @class = "btn btn-success pull-right" }) @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn btn-danger pull-right" })

 }

I Used this JQuery

Body:
$(window).load() has been removed in jQuery 3.0. Try using:

$(window).on('load', function () {
    $('#loading').hide();
});


问:
Got a "401 - Unauthorized" when trying my WCF Data service on IIS
I developed a WCF Data Service, which runs fine, I can do every operation I want through.

I developed a small c# client which tests all functions: adding, removing, modifying, retrieving data.

Everything works fine on my visual studio server, but once I'm on the IIS Server:

I can add/retrieve data

I cannot edit data

When I try to edit data I get this error:

System.Data.Services.Client.DataServiceRequestException was unhandled

  Message=Une erreur s'est produite lors du traitement de cette
  requête.

  Source=System.Data.Services.Client

  StackTrace:

  à System.Data.Services.Client.DataServiceContext.SaveResult.HandleBatchResponse()

  à System.Data.Services.Client.DataServiceContext.SaveResult.EndRequest()

  à System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions
  options)

  à System.Data.Services.Client.DataServiceContext.SaveChanges()

  à WSTester.Program.ModifySomeThings(Entities entities) dans
  D:\Workspace\10067.GfK

  Telecontrol.TOM\Release\V3.1\WSTester\Program.cs:ligne 90

  à WSTester.Program.Main(String[] args) dans
  D:\Workspace\10067.GfK
  Telecontrol.TOM\Release\V3.1\WSTester\Program.cs:ligne 23

  à System.AppDomain._nExecuteAssembly(RuntimeAssembly
  assembly, String[] args)

  à System.AppDomain.ExecuteAssembly(String assemblyFile,
  Evidence assemblySecurity, String[] args)

  à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

  à System.Threading.ThreadHelper.ThreadStart_Context(Object
  state)

  à System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  ignoreSyncCtx)

  à System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state)

  à System.Threading.ThreadHelper.ThreadStart()

  InnerException:

  System.Data.Services.Client.DataServiceClientException

  Message=
  Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      401 - Unauthorized: Access is denied due to invalid
  credentials.

.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
      -->

Server Error

401 - Unauthorized: Access is denied due to invalid
  credentials.

You do not have permission to view this directory or page
  using the credentials that you supplied.

Source=System.Data.Services.Client

  StatusCode=401

  StackTrace:

  à System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext()

  InnerException:

Which is strange, because I've all rights in my WCF Data service(and it works with visual studio), and I'm in anonymous mode in IIS, so I should have all rights to runs this query. IIS_USR has FULL CONTROL on the web folder, so I really don't see what can be the problem

答:
Try using the impersonation features of the app pool to user that has permissions. I have had many problems in the past using the default AppPoolIdentity features of IIS 7 and generally assign it to either a user setup for this very purpose or set it to use networkservice.

It is most likely that the pool doesn't have the proper permissions to execute properly.


问:
TypeScript empty object for a typed variable
Say I have:

```<code>type User = {
  ...
}
</code>```

I want to create a new user but set it to be an empty object:

```<code>const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use any
</code>```

How do I do this? I don't want the variable to be null.

答:
What i wanted is intellisense help for a chain of middlewares. Record<string, never> worked for me.

type CtxInitialT = Record<string, never>;
type Ctx1T = CtxInitialT & {
  name: string;
};
type Ctx2T = Ctx1T & {
  token: string;
};

cont ctx: CtxInitialT = {};
// ctx.name = ''; // intellisense error Type 'string' is not assignable to type 'never'
cont ctx1: Ctx1T = middleware1AugmentCtx(ctx);
// ctx1.name = 'ddd'; // ok
// ctx1.name1 = ''; // intellisense error Type 'string' is not assignable to type 'never'
cont ctx2: Ctx2T = middleware2AugmentCtx(ctx1);
// ctx2.token = 'ttt'; // ok
// ctx2.name1 = ''; // intellisense error Type 'string' is not assignable to type 'never'
```

Body:
Say I have:

type User = {
  ...
}

I want to create a new user but set it to be an empty object:

const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use any

How do I do this? I don't want the variable to be null.


问:
Basic Step function with error handling & SNS notification Improvement suggestions required
I have basic step function with error handling & SNS notification.

Need some suggestions &/or improvements and not sure if current process works.

Step1 glue job kicks off, If failed, needs to send SNS notification and do nothing.

If step1 glue job is successful then kick off Step2 glue job.

If step2 glue job is failed then SNS notification and done.

```<code>  "Comment": "A description of my state machine",
  "StartAt": "gluejob_step1",
  "States": {
    "gluejob_step1": {
      "Type": "Task",
      "Resource": "arn:aws:states:::glue:startJobRun.sync",
      "Parameters": {
        "JobName": "gluejob_step1"
      },
      "Catch": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "Next": "SNS Publish"
        }
      ],
      "Next": "gluejob_step2"
    },
    "gluejob_step2": {
      "Type": "Task",
      "Resource": "arn:aws:states:::glue:startJobRun.sync",
      "Parameters": {
        "JobName": "gluejob_step2"
      },
      "End": true,
      "Catch": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "Next": "SNS Publish"
        }
      ]
    },
    "SNS Publish": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "Message.$": "$"
      },
      "End": true
    }
  }
}
</code>```

答:
FWIW, I'm looking at a similar scenario. I don't have "best practices" to share  but I've taken a very similar approach to you.

I've defined "Next" on the SNS step to go to a "fail" state so that the overall status is failed - which is a truer representation of what has actually happened.

```<code>"FailState": {
    "Type": "Fail"
}
</code>```

Also, I have a requirement to update a sibling application of the failure so I've implemented a Lambda "in front" of the SNS step to fire a rest/http call. (Of course now I need to handle errors/failures there - :eyeroll:).

Best of luck, interested to see any other responses.

Body:
I have basic step function with error handling & SNS notification.

Need some suggestions &/or improvements and not sure if current process works.

Step1 glue job kicks off, If failed, needs to send SNS notification and do nothing.

If step1 glue job is successful then kick off Step2 glue job.

If step2 glue job is failed then SNS notification and done.

  "Comment": "A description of my state machine",
  "StartAt": "gluejob_step1",
  "States": {
    "gluejob_step1": {
      "Type": "Task",
      "Resource": "arn:aws:states:::glue:startJobRun.sync",
      "Parameters": {
        "JobName": "gluejob_step1"
      },
      "Catch": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "Next": "SNS Publish"
        }
      ],
      "Next": "gluejob_step2"
    },
    "gluejob_step2": {
      "Type": "Task",
      "Resource": "arn:aws:states:::glue:startJobRun.sync",
      "Parameters": {
        "JobName": "gluejob_step2"
      },
      "End": true,
      "Catch": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "Next": "SNS Publish"
        }
      ]
    },
    "SNS Publish": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "Message.$": "$"
      },
      "End": true
    }
  }
}

Body:
FWIW, I'm looking at a similar scenario. I don't have "best practices" to share  but I've taken a very similar approach to you.

I've defined "Next" on the SNS step to go to a "fail" state so that the overall status is failed - which is a truer representation of what has actually happened.

"FailState": {
    "Type": "Fail"
}

Also, I have a requirement to update a sibling application of the failure so I've implemented a Lambda "in front" of the SNS step to fire a rest/http call. (Of course now I need to handle errors/failures there - :eyeroll:).

Best of luck, interested to see any other responses.


问:
Spring Data JPA inserting underline character between variable words
Spring Data JPA inserts underscore character between words in variables, that does not happen if second term is not an word:

```<code>@Entity
@Table(name = "table")
public class Entity{
@Id
@GeneratedValue
private Long id;
private String variableA;
private String variableYes;
}
</code>```

For 'variableA' it creates table with variableA SQL text insertion, for 'variableYes' it inserts in SQL variable_Yes, I didn't found documentation for this particularity. Eclipse IDE console:

```<code>create table questao (id bigint not null, variableA char(255), variable_Yes varchar(255), primary key (id));
</code>```

答:
hibernate allow you define strategy. see:
https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#PhysicalNamingStrategy

You can define custom implementations of this PhysicalNamingStrategy. if you don't, i guess it use SpringPhysicalNamingStrategy as default strategy.

In SpringPhysicalNamingStrategy, it generate column name by property name use the below method:

```<code>private boolean isUnderscoreRequired(char before, char current, char after) {
        return Character.isLowerCase(before) && Character.isUpperCase(current) && Character.isLowerCase(after);
    }
</code>```

So, variableA is not match the rule, but variableYes match. And you database is casesensitive, so variableYes convert to variable_Yes, but variableA nothing changed.

Body:
Spring Data JPA inserts underscore character between words in variables, that does not happen if second term is not an word:

@Entity
@Table(name = "table")
public class Entity{
@Id
@GeneratedValue
private Long id;
private String variableA;
private String variableYes;
}

For 'variableA' it creates table with variableA SQL text insertion, for 'variableYes' it inserts in SQL variable_Yes, I didn't found documentation for this particularity. Eclipse IDE console:

create table questao (id bigint not null, variableA char(255), variable_Yes varchar(255), primary key (id));

Body:
hibernate allow you define strategy. see:
https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#PhysicalNamingStrategy

You can define custom implementations of this PhysicalNamingStrategy. if you don't, i guess it use SpringPhysicalNamingStrategy as default strategy.

In SpringPhysicalNamingStrategy, it generate column name by property name use the below method:

private boolean isUnderscoreRequired(char before, char current, char after) {
        return Character.isLowerCase(before) && Character.isUpperCase(current) && Character.isLowerCase(after);
    }

So, variableA is not match the rule, but variableYes match. And you database is casesensitive, so variableYes convert to variable_Yes, but variableA nothing changed.


答: Looks like you have a list of points in test and you have a list of areas describing the boundaries. I would use spatial joining for filtering a table of points e.g. using function st_within of R package sf

Title: r - lapply/loop or outer with two indices

Body:
I have a dataset v1 where I want to get data of certain grid boxes.

Here's an extract from v1:

"V1" "V2" "V3" "V4" "V5" "V6" "V7" "V8" "V9" "V10" "V11" "V12" "V13" "V14" "V15" "V16" "V17" "V18"
43 1 0 69 60 9 19501201 1080 0 1 641 30 0 291 272 136 29 3650
43 1 1 69 60 9 19501201 884 0 1 705 30 3 290 293 136 29 3650
43 1 2 70 61 9 19501201 553 293 1 1090 30 6 264 468 138 31 3650
43 1 3 71 62 9 19501201 416 290 1 1240 30 9 303 503 140 33 3650
43 1 4 72 63 9 19501201 396 287 1 1160 30 12 334 444 142 35 3650
43 1 5 73 64 9 19501201 163 285 1 1440 30 15 377 687 144 37 3650
43 1 6 74 66 9 19501201 29 475 1 1490 30 18 386 674 146 41 3650
43 1 7 74 67 9 19501201 -257 222 1 1960 30 21 444 875 146 43 3650
43 1 8 74 68 9 19501202 -216 222 1 1850 30 0 438 806 146 45 3650
43 1 9 74 69 9 19501202 -393 222 1 1950 30 3 444 847 146 47 3650
43 1 10 74 70 9 19501202 -500 222 1 2130 30 6 457 901 146 49 3650

The list "v1" has the columns longitudes (V16) and the latitudes (V17) of the boundary conditions you see below.

For example, I need to filter between 80°W-30°E (V16) and 25°N-75°N (V17) by boxes of 5° each.

I want to keep all other columns from the filtered-out box.

These are my boundary conditions:

lon1_i <- seq(-80,25, by=5)

lon2_i <- seq(-75,30, by=5)

lat1_i <- seq(25,70, by=5)

lat2_i <- seq(30,75, by=5)

So the first grid box has all the info in -80° to -75° and 25°-30°, then the second box contains the data from -75° to -70° and 30°-35°. And so on until the last box of 25°-30°E and 70°-75°N.

I tried to use a for loop with two indices:

for (i in 1:22) {

  for(k in 1:10) {

    test[[i]][[k]] <- v1 %>%

      filter(between(V16, lon1_i[[i]], lon2_i[[i]]), between(V17, lat1_i[[k]], lat2_i[[k]])) %>%

      group_by(group = cumsum(V3 == 0))
 }
}

And with outer:

test <- outer(seq(lon1_i),seq(lon2_i),seq(lat1_i),seq(lat2_i),

              function(i,j) v1 %>%

        filter(between(V16, lon1_i[i], lon2_i[i]),
               between(V17, lat1_i[j], lat2_i[j])) %>%
        group_by(group = cumsum(V3 == 0)))

Also lapply:

test <- lapply(seq(22,10),function(x) v1 %>%

        filter(between(V16, lon1_i[x], lon2_i[x]), between(V17, lat1_i[x], lat2_i[x])) %>%

                   group_by(group = cumsum(V3 == 0)))

The output should be in the form of new data tables/lists so I guess 22x10 from my chosen coordinates.
Is it possible with these functions/types of loops? I would much appreciate some help on this. Thanks!


问:
Kafka Debezium Connector Working But not ingesting data into PostgreSQL
I have successfully connect postgresql to kafka using debezium-connector-postgres-1.8.0.Final-plugin connector.Below is my Standalone.properties file:

```<code>rest.port=8084
bootstrap.servers=localhost:9092

key.converter=org.apache.kafka.connect.storage.StringConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
value.converter.schemas.enable=false

offset.storage.file.filename=/tmp/connect.offsets
offset.flush.interval.ms=10000

plugin.path=/home/abc/debezium-connector-postgres-1.8.0.Final-plugin/debezium-connector-postgres/debezium-connector-postgres-1.8.0.Final.jar,

############################# Zookeeper #############################

zookeeper.connect=localhost:2181

</code>```

My connector file is given below:

```<code>name= inventory_db-connector
connector.class= io.debezium.connector.postgresql.PostgresConnector
tasks.max= 1
database.hostname= localhost
database.port= 5432
database.user= user
database.password= pass
database.dbname = testdb
database.server.name= dbserver1
database.whitelist= testdb
database.history.kafka.bootstrap.servers= kafka=9092
database.history.kafka.topic= schema-changes.inventory
topics=inventory
topic.inventory.inventory.conditions.mapping=time=value.time,device_id=value.device_id,temperature=value.temperature,humidity=value.humidity
</code>```

It is running successfully on the terminal through the following command kafka/bin/connect-standalone.sh kafka/config/connect-standalone.properties /home/abc/inventory_db-connector.

My inventory.txt contains the data which i want to ingest in the database in the JSON format.
Also I have checked on kafka-consumer for inventory topic and it shows that data is loaded:

```<code>{"time":"2022-02-08 16:18:00-05", "device_id":"weather-pro001000", "temperature":"200", "humidity":"200"}
</code>```

Now we are trying to ingest the data into postgres using the following command cat inventory.txt | kafka/bin/kafka-console-producer.sh   --broker-list localhost:9092   --topic demo   --property "parse.key=true"   --property "key.separator=:";
But now the problem is that data is not inserted in the database and the command does
not shows any error and my log is also empty.
I cannot seem to figure out this problem.

答:
Debezium connector is a source connector i.e it is used to read data from postgresSQL into kafka.

If you want to ingest data into postgres sql try using JDBC sink connector

https://docs.confluent.io/kafka-connect-jdbc/current/sink-connector/index.html

Body:
I have successfully connect postgresql to kafka using debezium-connector-postgres-1.8.0.Final-plugin connector.Below is my Standalone.properties file:

rest.port=8084
bootstrap.servers=localhost:9092

key.converter=org.apache.kafka.connect.storage.StringConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
value.converter.schemas.enable=false

offset.storage.file.filename=/tmp/connect.offsets
offset.flush.interval.ms=10000

plugin.path=/home/abc/debezium-connector-postgres-1.8.0.Final-plugin/debezium-connector-postgres/debezium-connector-postgres-1.8.0.Final.jar,

############################# Zookeeper #############################

zookeeper.connect=localhost:2181

My connector file is given below:

name= inventory_db-connector
connector.class= io.debezium.connector.postgresql.PostgresConnector
tasks.max= 1
database.hostname= localhost
database.port= 5432
database.user= user
database.password= pass
database.dbname = testdb
database.server.name= dbserver1
database.whitelist= testdb
database.history.kafka.bootstrap.servers= kafka=9092
database.history.kafka.topic= schema-changes.inventory
topics=inventory
topic.inventory.inventory.conditions.mapping=time=value.time,device_id=value.device_id,temperature=value.temperature,humidity=value.humidity

It is running successfully on the terminal through the following command kafka/bin/connect-standalone.sh kafka/config/connect-standalone.properties /home/abc/inventory_db-connector.

My inventory.txt contains the data which i want to ingest in the database in the JSON format.
Also I have checked on kafka-consumer for inventory topic and it shows that data is loaded:

{"time":"2022-02-08 16:18:00-05", "device_id":"weather-pro001000", "temperature":"200", "humidity":"200"}

Now we are trying to ingest the data into postgres using the following command cat inventory.txt | kafka/bin/kafka-console-producer.sh   --broker-list localhost:9092   --topic demo   --property "parse.key=true"   --property "key.separator=:";
But now the problem is that data is not inserted in the database and the command does
not shows any error and my log is also empty.
I cannot seem to figure out this problem.


问:
How can javaScript library and css files load before component load in reactjs
How can javaScript library and css files load before reactjs component load.

I am converting dataTable Html template  to react component but javaScript library and css files are isn't loaded with components.

How can I solved it. Can any one help me?

答:
You can try to use import [ which js library you want to use ]
and then put this syntax at the js file top like as you import react;

import $ from 'jquery';```