问:
Can I have a different controller called based on the value of request parameters?
I designed BoardController for making boards, and FirstBoardController for FirstBoard implemented by inheriting this Board entity.

@Entity
public class Board{
  protected Long id;

  protected String name;

  protected String contents;

  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "menu_id", foreignKey =
  @ForeignKey(name = "fk_board_to_menu"))
  protected Menu menu;
}

@Entity
public class FirstBoard extends Board{
  // add additional fields
}
```
<p>FirstBoard is an entity with some additional fields added to Board,
and I want to call FirstBoardController based on the menuId received as a parameter when calling 'getBoardList' method from BoardController.</p>
<pre class="lang-java prettyprint-override"><code>@Controller
public class BoardController {

    public Page<BoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return boardService.getBoardList(menuId, pageable);
    }
}

@Controller
@RequiredArgsConstructor
public class FirstBoardController {

    private final FirstBoardService firstBoardService;

    public Page<FirstBoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return firstBoardService.getBoardList(menuId, pageable);
    }
}
</code>```

I can't categorize posts via menuId in the usual way. This is because the DTO returned by getBoardList of FirstBoardController and the Service object used are also different from BoardController.

For example, if board?menuId=1 is entered in the URL,
the getBoardList method of FirstBoardController is called, and if board?menuId=2 is entered in the URL, SecondBoardController (to be added later) is called.

The point is, I want to designate BoardController as the upper controller and treat the controller of the entity implemented by inheriting the value of Board Entity as menuId, a parameter of the function defined in BoardController.

After a little research, it seems that I can use HandlerMapping, but I have no idea how to do it.

Can you answer anything to me about this subject?

答:
i think you can use GetMapping#params/RequestMapping#params to achieve your goal.</p>
```<code>@Controller
//Depends on your actual needs, the org.springframework.web.bind.annotation.RequestMapping#params may be using in here
public class BoardController {
    @GetMapping(params = "menuId=1") //when the menuId=1, it mapping match this method
    public Page<BoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return boardService.getBoardList(menuId, pageable);
    }
}

@Controller
@RequiredArgsConstructor
public class FirstBoardController {

    private final FirstBoardService firstBoardService;
    @GetMapping(params = "menuId=2") //when the menuId=2, it mapping match this method
    public Page<FirstBoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return firstBoardService.getBoardList(menuId, pageable);
    }
}
</code>```

Body:
I designed BoardController for making boards, and FirstBoardController for FirstBoard implemented by inheriting this Board entity.

@Entity
public class Board{
  protected Long id;

  protected String name;

  protected String contents;

  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "menu_id", foreignKey =
  @ForeignKey(name = "fk_board_to_menu"))
  protected Menu menu;
}

@Entity
public class FirstBoard extends Board{
  // add additional fields
}

FirstBoard is an entity with some additional fields added to Board,
and I want to call FirstBoardController based on the menuId received as a parameter when calling 'getBoardList' method from BoardController.

@Controller
public class BoardController {

    public Page<BoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return boardService.getBoardList(menuId, pageable);
    }
}

@Controller
@RequiredArgsConstructor
public class FirstBoardController {

    private final FirstBoardService firstBoardService;

    public Page<FirstBoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return firstBoardService.getBoardList(menuId, pageable);
    }
}

I can't categorize posts via menuId in the usual way. This is because the DTO returned by getBoardList of FirstBoardController and the Service object used are also different from BoardController.

For example, if board?menuId=1 is entered in the URL,
the getBoardList method of FirstBoardController is called, and if board?menuId=2 is entered in the URL, SecondBoardController (to be added later) is called.

The point is, I want to designate BoardController as the upper controller and treat the controller of the entity implemented by inheriting the value of Board Entity as menuId, a parameter of the function defined in BoardController.

After a little research, it seems that I can use HandlerMapping, but I have no idea how to do it.

Can you answer anything to me about this subject?

Body:
i think you can use GetMapping#params/RequestMapping#params to achieve your goal.

@Controller
//Depends on your actual needs, the org.springframework.web.bind.annotation.RequestMapping#params may be using in here
public class BoardController {
    @GetMapping(params = "menuId=1") //when the menuId=1, it mapping match this method
    public Page<BoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return boardService.getBoardList(menuId, pageable);
    }
}

@Controller
@RequiredArgsConstructor
public class FirstBoardController {

    private final FirstBoardService firstBoardService;
    @GetMapping(params = "menuId=2") //when the menuId=2, it mapping match this method
    public Page<FirstBoardDto> getBoardList(
            Pageable pageable,
            @RequestParam Integer menuId
    ) {
        return firstBoardService.getBoardList(menuId, pageable);
    }
}


来源: stackexchange

问:
How to query in mysql when involving more than one table?
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

```<code>Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED
</code>```

答:
I think, you can try this query :

```<code>SELECT A.ID, A.'NUMBER OF ORDER', B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE B.STATUS = 'COMPLETED'
</code>```

more information about inner join, you can learn on W3S https://www.w3schools.com/sql/sql_join_inner.asp

ContentLicense: CC BY-SA 4.0

Body:
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED

Body:
I think, you can try this query :

SELECT A.ID, A.'NUMBER OF ORDER', B.STATUS
FROM A
INNER JOIN B ON A.ID = B.A_ID
WHERE B.STATUS = 'COMPLETED'

more information about inner join, you can learn on W3S https://www.w3schools.com/sql/sql_join_inner.asp


问:
Amazon SP-API Getting order items in order list API
The Amazon SP-API getorders API endpoint doesn't send the items of that orders. I want to show the orders with their items like in Amazon Seller central in my inventory. Calling the get items (getorderitems endpoint) for every order will be unwise. Is there any other way to achieve this?

The seller central sends the order items data altogether in a single response.

答:
SP-API was specifically set up to not include all that data in one API call. They provide the following operations for you to be able to get the specific data you need:

getOrders

getOrder

getOrderBuyerInfo

getOrderAddress

getOrderItems

getOrderItemsBuyerInfo

updateShipmentStatus

orders-api

So for each order you need to call the getOrderItems operation to retrieve the data you are looking for.


问:
How do I open up a page on selenium python
```<code>driver = webdriver.Chrome()
driver.get("https://www.nytimes.com/games/wordle/index.html")
driver.maximize_window()
time.sleep(3)
button = driver.find_element_by_link_text("x")
button.click()
</code>```

I have this code to open up wordle on python, but I do not know how to actually make it show the page. Please help! Also if anyone would like to help me along the process of learning how to make a bot to play wordle I would appreciate any help or tips.

答: There seems to be nothing wrong with the code, have you checked to make sure it isn't a problem with the environment or packages? What version of python are you using?</p>

Body:
driver = webdriver.Chrome()
driver.get("https://www.nytimes.com/games/wordle/index.html")
driver.maximize_window()
time.sleep(3)
button = driver.find_element_by_link_text("x")
button.click()

I have this code to open up wordle on python, but I do not know how to actually make it show the page. Please help! Also if anyone would like to help me along the process of learning how to make a bot to play wordle I would appreciate any help or tips.


问:
React Native Async Storage : where are information storage at?Phone or App?
I am using Async storage in RN. A teaching video said the async storage is global storage. What does it mean? It is mean my data can be found from my phone or only from the app?( when I delete the app from phone, can I still find that information on phone?)

Besides, what's the size limitation of Async storage? Can I use it to store image or document?

答:
AsyncStorage's documentation actually has the answer to your question

AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app.

So if you've deleted your app, the data will be gone.

As to the size limitation of AsyncStorage, it is currently set to 6MB.

You can store literally anything as long as it is in string format, so if let's say you wish to store an image, convert it to base64 string, and store it, and when you need to retrieve or show the image, AsyncStorage.getItem gives you back the base64 string, convert it back to an image before showing it


问:
How to display the image in the notification
I recently used FirebasePushNotificationPlugin in my application and everything is fine...
But when I send a notification, the image is not displayed and all other texts are displayed
I've searched and tried but to no avail:
This is the link for the tool:
https://github.com/CrossGeeks/FirebasePushNotificationPlugin
And this is my code:
Andriod:

```<code>[Application]
public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();

        //Set the default notification channel for your app when running Android Oreo
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            //Change for your default notification channel id here
            FirebasePushNotificationManager.DefaultNotificationChannelId = "GeneralChannel";
            //Change for your default notification channel name here
            FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
            FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
        }
        //If debug you should reset the token each time.
#if DEBUG
            FirebasePushNotificationManager.Initialize(this, true);
#else
            FirebasePushNotificationManager.Initialize(this, false);
#endif

        //Handle notification when app is closed here
        CrossFirebasePushNotification.Current.OnNotificationReceived += Current_OnNotificationReceived;

    }

    private void Current_OnNotificationReceived(object source, FirebasePushNotificationDataEventArgs e)
    {

    }
}
</code>```

MainActivity:

```<code>FirebasePushNotificationManager.ProcessIntent(this, Intent);
</code>```

In Backend I used FireBase Admin Plugin :

```<code>public async void SendToAllUser(Notification notification, Dictionary<string, string> MsgData)
        {
            var message = new Message()
            {
                Data = MsgData,
                Topic = "all",
                Notification = notification,
                Apns = new ApnsConfig
                {
                    Aps = new Aps
                    {
                        ContentAvailable = true,
                        MutableContent = true
                    }
                }
            };
            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
            Console.WriteLine("Successfully sent message: " + response);
        }
</code>```

Notification Controller:

```<code>[HttpPost("UserName={UserName}&Password={Password}&Key={Key}&Value={Value}")]
        public ActionResult<Notification> SendToAllDevice(string UserName, string Password, string Key, string Value, Notification notification)
        {
            int UserRole = URole.CheckUserRolee(UserName, Password);
            if (UserRole != 1)
            {
                return StatusCode(403);
            }
            var Dataa = new Dictionary<string, string>() { { Key, Value } };
            SendFCMessage.SendToAllUser(notification, Dataa);
            return Ok();
        }
</code>```

答:
Make sure you add the key and value(image url) in FCM console and handle it with the service you write.

You can refer to this question https://learn.microsoft.com/en-us/answers/questions/541284/xamarin-forms-firebase-notification-ui.html

And also here is a sample:https://github.com/xamarin/monodroid-samples/tree/main/Firebase/FCMNotifications/FCMNotifications

edit:

```<code> <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/notification_channel_id" />
</code>```

Body:
I recently used FirebasePushNotificationPlugin in my application and everything is fine...
But when I send a notification, the image is not displayed and all other texts are displayed
I've searched and tried but to no avail:
This is the link for the tool:
https://github.com/CrossGeeks/FirebasePushNotificationPlugin
And this is my code:
Andriod:

[Application]
public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();

        //Set the default notification channel for your app when running Android Oreo
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            //Change for your default notification channel id here
            FirebasePushNotificationManager.DefaultNotificationChannelId = "GeneralChannel";
            //Change for your default notification channel name here
            FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
            FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
        }
        //If debug you should reset the token each time.
#if DEBUG
            FirebasePushNotificationManager.Initialize(this, true);
#else
            FirebasePushNotificationManager.Initialize(this, false);
#endif

        //Handle notification when app is closed here
        CrossFirebasePushNotification.Current.OnNotificationReceived += Current_OnNotificationReceived;

    }

    private void Current_OnNotificationReceived(object source, FirebasePushNotificationDataEventArgs e)
    {

    }
}

MainActivity:

FirebasePushNotificationManager.ProcessIntent(this, Intent);

In Backend I used FireBase Admin Plugin :

public async void SendToAllUser(Notification notification, Dictionary<string, string> MsgData)
        {
            var message = new Message()
            {
                Data = MsgData,
                Topic = "all",
                Notification = notification,
                Apns = new ApnsConfig
                {
                    Aps = new Aps
                    {
                        ContentAvailable = true,
                        MutableContent = true
                    }
                }
            };
            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
            Console.WriteLine("Successfully sent message: " + response);
        }

Notification Controller:

[HttpPost("UserName={UserName}&Password={Password}&Key={Key}&Value={Value}")]
        public ActionResult<Notification> SendToAllDevice(string UserName, string Password, string Key, string Value, Notification notification)
        {
            int UserRole = URole.CheckUserRolee(UserName, Password);
            if (UserRole != 1)
            {
                return StatusCode(403);
            }
            var Dataa = new Dictionary<string, string>() { { Key, Value } };
            SendFCMessage.SendToAllUser(notification, Dataa);
            return Ok();
        }

Body:
Make sure you add the key and value(image url) in FCM console and handle it with the service you write.

You can refer to this question https://learn.microsoft.com/en-us/answers/questions/541284/xamarin-forms-firebase-notification-ui.html

And also here is a sample:https://github.com/xamarin/monodroid-samples/tree/main/Firebase/FCMNotifications/FCMNotifications

edit:

 <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/notification_channel_id" />


问:
What do people mean when they talk about serialization in Unity?
I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using

```<code>[SerializeField]
</code>```

and don't know why or what it does.

答:
I looked up the definition of data serialization: Serialization is the process of converting the state information of an object into a form that can be stored or transmitted.

During serialization, objects write their current state to temporary or persistent storage. Later, the object can be recreated by reading or deserializing the state of the object from the store.

Objects are created as the program runs, and then reclaimed when unreachable, with a short lifespan. But what if we want to store the contents of the object permanently?

Convert it into a sequence of bytes and save it on a storage medium. Then serialization is required. [SerializeField] is to force Unity to serialize a private field. This is an internal Unity serialization function. Sometimes we need to Serialize a private or protected attribute. In this case, the [SerializeField] attribute can be used.

The above is some information I found, I hope it is correct and can bring you some help

Body:
I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using

[SerializeField]

and don't know why or what it does.


问:
Read Excel File Using Openpyxl
I want to save each Row of an excel file in a list using openpyxl.

```<code>wb = load_workbook('Shop.xlsx')
ws = wb.active

l = []

a_column = ws['A']
b_column = ws['B']

for x in range(len(a_column)):
    l.append([a_column[x].value, b_column[x].value])

print(l)
</code>```

Output: [[A1, B1], [A2, B2]]

It works but does anyone know a better way?

The list, for example, only works through the length of A.

答:
You can do this in one line with ws.iter_rows()

l = [row for row in ws.iter_rows(max_col=2, values_only=True)]
```

Good to note that the maximum column length openpyxl finds in Excel can be influenced by cells containing None below where you think your data ends.

Title: Read Excel File Using Openpyxl

Body:
I want to save each Row of an excel file in a list using openpyxl.

wb = load_workbook('Shop.xlsx')
ws = wb.active

l = []

a_column = ws['A']
b_column = ws['B']

for x in range(len(a_column)):
    l.append([a_column[x].value, b_column[x].value])

print(l)

Output: [[A1, B1], [A2, B2]]

It works but does anyone know a better way?

The list, for example, only works through the length of A.

Body:
You can do this in one line with ws.iter_rows()

l = [row for row in ws.iter_rows(max_col=2, values_only=True)]

Good to note that the maximum column length openpyxl finds in Excel can be influenced by cells containing None below where you think your data ends.


问:
How does a function know what inputs to draw from when labeled under different names?
How can int length and int array[] be labeled differently than int TOTAL and int scores, yet they are recognized as being the same in the average() function? I assumed they had to be called the same thing in order to be recognized?

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

float average();

const int TOTAL = 3;

int main(void)
{
    int scores[TOTAL];
    for (int i = 0; i < TOTAL; i++)
        {
        scores[i] = get_int("Score: ");
        }

    printf("Average: %f\n", average(TOTAL, scores));

}

//int array [] same as saying int scores [] ?
//int 'length' same as saying 'TOTAL' ?
float average(int length, int array[])
{
    int sum = 0;
    for (int i = 0; i < length; i++)
    {
        sum += array[i];
    }
    return sum / (float) length;
}
</code>```

答:
In this case, the arguments are called positional.

This means, that when you define a function (float average(int length, int array[]){...}), length will be the firs argument and array will be the second. These names are not global and exist only inside the function.

When you call the function (average(TOTAL, scores)), you pass global (availiable from everywhere) variable TOTAL as the first argument, and a local for main function variable scores as the second argument.

length is not the same as TOTAL, it just gets the value of TOTAL when the function is called. Same for array and scores.

Body:
How can int length and int array[] be labeled differently than int TOTAL and int scores, yet they are recognized as being the same in the average() function? I assumed they had to be called the same thing in order to be recognized?

#include <cs50.h>
#include <stdio.h>

float average();

const int TOTAL = 3;

int main(void)
{
    int scores[TOTAL];
    for (int i = 0; i < TOTAL; i++)
        {
        scores[i] = get_int("Score: ");
        }

    printf("Average: %f\n", average(TOTAL, scores));

}

//int array [] same as saying int scores [] ?
//int 'length' same as saying 'TOTAL' ?
float average(int length, int array[])
{
    int sum = 0;
    for (int i = 0; i < length; i++)
    {
        sum += array[i];
    }
    return sum / (float) length;
}


问:
Rails - Handle User roles using pundit
I have a table of users with enum user_type [Manager, Developer, QA]. Currently, I'm handling sign in using Devise and after login I'm using the following logic to display the appropriate webpage:

```<code>class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    if current_user.manager?
      redirect_to manager_path(current_user.id)
    end
    if current_user.developer?
      redirect_to developer_path(current_user.id)
    end
    if current_user.quality_assurance?
      redirect_to qa_path(current_user.id)
    end
  end
end
</code>```

I want to use pundit gem to handle this. From the documentation, it transpired that this logic will be delegated to policies but I can't figure out how. Can somebody help me in implementing pundit in my project?

This is my users table:

I have created a user_policy but its mostly empty:

```<code>class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.all
    end
  end
end
</code>```

User model:

答:
You want to use Pundit to authorize a user, as in check if that user should be allowed to visit a controller action. If the user is not authorized for a specific action it raises a Pundit::NotAuthorizedError

You can check if a user is allowed to perform an action in the pundit policy, in which you have access to record (the instance thats passed to authorize) and user. So assuming you have a Flat Model, where only the owner can edit the Flat you might do this:

# flats_policy.rb
def edit?
  record.user == user
end
```
<p>Now lets say you also want to allow admins to edit you might do this</p>
<pre class="lang-rb prettyprint-override"><code># flats_policy.rb
def owner_or_admin?
  record.user == user || user.admin # where admin is a boolean
end

def edit?
  owner_or_admin?
end
</code>```

and the controller:

# flats_controller.rb
def edit
  @flat = Flat.find(params[:id])
  authorize @flat
  # other code here
end
```
<p>Now the <strong>index</strong> action is the odd one out because you would essentially have to call <code>authorize</code> on each instance, so the way Pundit handles this is with the Scope:</p>
<pre class="lang-rb prettyprint-override"><code># flats_policy.rb
class Scope < Scope
  def resolve
    scope.all
  end
end
</code>```

and a corresponding index action might look like:

def index
  @flats = policy_scope(Flat) # note that we call the model here
end
```
<p>So lets say a user can only see flats that he/she owns:</p>
<pre class="lang-rb prettyprint-override"><code># flats_policy.rb
class Scope < Scope
  def resolve
    scope.where(user: user)
  end
end
</code>```

and if admins can see all flats:

# flats_policy.rb
class Scope < Scope
  def resolve
    if user.admin
      scope.all
    else
      scope.where(user: user)
    end
  end
end
```
<p>In any case if the user is not allowed to perform an action you can rescue from the error like so:</p>
<pre class="lang-rb prettyprint-override"><code># application_controller
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def user_not_authorized
  flash[:alert] = "You are not authorized to perform this action."
  redirect_to(root_path)
end
</code>```

I guess you could do some dirty redirecting here, as in send admins to an admins_root_path, users to a default_root_path and so on...

On a final note, since this post is already too long you can check a policy in the view like this:

```<code><% if policy(restaurant).edit? %>
  You can see me if you have edit rights
<% end %>
</code>```

Title: Rails - Handle User roles using pundit

Body:
I have a table of users with enum user_type [Manager, Developer, QA]. Currently, I'm handling sign in using Devise and after login I'm using the following logic to display the appropriate webpage:

class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    if current_user.manager?
      redirect_to manager_path(current_user.id)
    end
    if current_user.developer?
      redirect_to developer_path(current_user.id)
    end
    if current_user.quality_assurance?
      redirect_to qa_path(current_user.id)
    end
  end
end

I want to use pundit gem to handle this. From the documentation, it transpired that this logic will be delegated to policies but I can't figure out how. Can somebody help me in implementing pundit in my project?

This is my users table:

I have created a user_policy but its mostly empty:

class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.all
    end
  end
end

User model:

Body:
You want to use Pundit to authorize a user, as in check if that user should be allowed to visit a controller action. If the user is not authorized for a specific action it raises a Pundit::NotAuthorizedError

You can check if a user is allowed to perform an action in the pundit policy, in which you have access to record (the instance thats passed to authorize) and user. So assuming you have a Flat Model, where only the owner can edit the Flat you might do this:

# flats_policy.rb
def edit?
  record.user == user
end

Now lets say you also want to allow admins to edit you might do this

# flats_policy.rb
def owner_or_admin?
  record.user == user || user.admin # where admin is a boolean
end

def edit?
  owner_or_admin?
end

and the controller:

# flats_controller.rb
def edit
  @flat = Flat.find(params[:id])
  authorize @flat
  # other code here
end

Now the index action is the odd one out because you would essentially have to call authorize on each instance, so the way Pundit handles this is with the Scope:

# flats_policy.rb
class Scope < Scope
  def resolve
    scope.all
  end
end

and a corresponding index action might look like:

def index
  @flats = policy_scope(Flat) # note that we call the model here
end

So lets say a user can only see flats that he/she owns:

# flats_policy.rb
class Scope < Scope
  def resolve
    scope.where(user: user)
  end
end

and if admins can see all flats:

# flats_policy.rb
class Scope < Scope
  def resolve
    if user.admin
      scope.all
    else
      scope.where(user: user)
    end
  end
end

In any case if the user is not allowed to perform an action you can rescue from the error like so:

# application_controller
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def user_not_authorized
  flash[:alert] = "You are not authorized to perform this action."
  redirect_to(root_path)
end

I guess you could do some dirty redirecting here, as in send admins to an admins_root_path, users to a default_root_path and so on...

On a final note, since this post is already too long you can check a policy in the view like this:

<% if policy(restaurant).edit? %>
  You can see me if you have edit rights
<% end %>


问:
How to import a dialog (and code) to libreoffice calc
I had written some code and a small dialog for simplifying some processes for an older version of calc.

In order to load a dialog in the old versions of calc, i could go to the menu "Tools | Macros | Organize Dialogs", choose "import dialog" (an icon showing a document with a plus symbol) and then load my dialog resource ("dlgCSVLoad.xdl")

In the current version (7.2.5.2) there seems to be no (obvious) possibility to load a dialog resource anymore.

What steps do i have to take to import a dialog resource (in xdl format) into libreoffice calc?

答:
Edit an existing dialog. You can create a new one for this purpose if you want. Then go to File > Import Dialog.

It's also possible to copy the file directly into a library under the basic directory in your LibreOffice user profile. Then edit dialog.xlb to tell it which file you added.


问:
Pre-defined infix operator list in Haskell?
Basically, I need to define infix operator for function composition, flipped g . f manner.

```<code>(#) :: (a -> b) -> (b -> c) -> a -> c
(#) = flip (.)

infixl 9 #
</code>```

Here, temporarily, I just have chosen the symbol: #, but I'm not certain this choice is not problematic in terms of collision to other definitions.

The weird thing is somehow I could not find a Pre-defined infix operator list in Haskell.

I want the composition operator as concise as possible, hopefully, a single character like ., and if possible, I want to make it &. Is it OK?

Is there any guidance or best pracice tutorial? Please advise.

Related Q&A:

What characters are permitted for Haskell operators?

答:
You don't see a list of Haskell built-in operators for the same reason you don't see a list of all built-in functions. They're everywhere. Some are in Prelude, some are in Control.Monad, etc., etc. Operators aren't special in Haskell; they're ordinary functions with neat syntax. And Haskellers are generally pretty operator-happy in general. Spend any time inside your favorite lens library and you'll find plenty of amusing-looking operators.

In terms of (#), it might be best to avoid. I don't know of any built-in operators called that, but # can be a bit special when it comes to parsing. Specifically, a compiler extension enables # at the end of ordinary identifiers, and GHC defines a lot of built-in (primitive) types following this practice. For instance, Int is the usual (boxed) integer type, whereas Int# is a primitive integer. Most people don't need to interface with this directly, but it is a use that # has in Haskell that would be confused slightly by the addition of your operator.

Your (#) operator is called (>>>) in Haskell, and it works on all Category instances, including functions. Its companion is (<<<), the generalization of (.) to all Category instances. If three characters is too long for you, I've seen it called (|>) in some other languages, but Haskell already uses that operator for something else. If you're not using Data.Sequence, you could use that operator. But personally, I'd just go with (>>>). Any Haskeller will recognize it pretty quickly.

Body:
Basically, I need to define infix operator for function composition, flipped g . f manner.

(#) :: (a -> b) -> (b -> c) -> a -> c
(#) = flip (.)

infixl 9 #

Here, temporarily, I just have chosen the symbol: #, but I'm not certain this choice is not problematic in terms of collision to other definitions.

The weird thing is somehow I could not find a Pre-defined infix operator list in Haskell.

I want the composition operator as concise as possible, hopefully, a single character like ., and if possible, I want to make it &. Is it OK?

Is there any guidance or best pracice tutorial? Please advise.

Related Q&A:

What characters are permitted for Haskell operators?


问:
Not in table between dates
I have 2 tables :

terminal

```<code>id   text
1    abc
2    def
3    dfg
</code>```

termusage

```<code>id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13
</code>```

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

```<code>select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)
</code>```

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers

答:
```<code>SELECT t.id FROM usage u
    INNER JOIN terminal t ON t.id = u.termid AND u.date NOT BETWEEN '2010-11-01' and '2010-12-01'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Not in table between dates

Body:
I have 2 tables :

terminal

id   text
1    abc
2    def
3    dfg

termusage

id  termid   date
1   1        2010-11-01
2   1        2010-10-13
3   2        2010-11-10
4   3        2010-11-13

+ many more records (10 million) approv half are within the date (2010-11-01 and 2010-12-01)

What i want to do is find the terminal.id of the records that do not exist in the termusage table between 2010-11-01 and 2010-12-01

I have looked at select where not exists but nothing is being returned - example

select * from terminal
where not exists (
select * from termusage where date between '2010-11-01' and '2010-12-01' group by termid)

Can anyone please explain how i need to use the where not exists clause or another method !! Cheers


问:
Cloudflare Pages - Cloudflare Workers
So i started to get my hands dirty with cloudflare pages and workers

My thought is

get a domain mydomain.com (done)

make a static site @ github myaccount.github.io (done)

make a cloudflare pages page add CNAME to DNS ZONE (done) so myaccount.github.io can be @ my-official-site.com (done)

make a cloudflare worker https://myworker.myclaccount.workers.dev (done)

So when i request my-official-site.com i get the content of myaccount.github.io

Now i want to run from my myaccount.github.io a worker to get some html or json or....

I trying to fetch from my myaccount.github.io (index.html)

```<code><script>
fetch('https://myworker.myclaccount.workers.dev')
  .then(response => response.json())
  .then(data => console.log(data));
</script>
</code>```

I get the request to my worker like this

```<code>const html =
  "<p>This markup was generated by a Cloudflare Worker.</p>"

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})
</code>```

The problem is

```<code>Access to fetch at 'https://myworker.myclaccount.workers.dev/'
from origin 'my-official-site.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

I create a

_headers.txt   (https://developers.cloudflare.com/pages/platform/headers) at the root of my github "site" with this

```<code>/*
  Access-Control-Allow-Origin: *
</code>```

but the same...

I'm new to serverless and jamstack (i now js, css, html) but new to this concept

knowledge (android, c#, php, wp, unity, some node.js)

Thank you for your help.

答:
You don't seem to be using Cloudflare Pages. Such deploy would for the most part replace your current Github Pages + Cloudflare Workers combo, and you wouldn't deal with cross-site requests for the use case you've shown.

Even if you mean to keep using workers as a separate augmentation tool, enabling CORS in your current setup is missing the point. Workers can be transparently mounted on any route of your domain, therefore turning cross-site requests into same-origin even if the real servers are half a planet away.

Anyway, there are for sure several use cases for CORS in workers. For a basic example, here's a simple middleware that takes a Response or a promise of one, returning a copy with modified headers. (There's a lot more to CORS, but that's out of this question's scope)

```<code>/**
 * @param {Response|Promise<Response>} res
 * @returns {Promise<Response>}
 */
async function corsEnabler(res) {
   res = await res
   const corsResponse = new Response(res.body, res)
   corsResponse.headers.set('Access-Control-Allow-Origin','*')
   corsResponse.headers.set('Access-Control-Allow-Methods','GET,POST,HEAD,OPTIONS')
   return corsResponse
}
</code>```

(I'm awaiting res in case I'm passed the promise of a response. But this doesn't mean awaiting for its contents!) Then, where your code says

```<code>addEventListener("fetch", event => {
   return event.respondWith(
         handleRequest(event.request)
   )
})
</code>```

You would use the middleware like

```<code>addEventListener("fetch", event => {
   return event.respondWith(
        corsEnabler( handleRequest(event.request) )
   )
})
</code>```

If you were using module syntax you would use a default export instead of a FetchEvent

```<code>export default {
  fetch(request, env, context) {
    return corsEnabler( handleRequest(request) )
  }
}
</code>```

And if you used page functions:

```<code>export async function onRequest(context) {
   return corsEnabler( handleRequest(context.request) )
}
</code>```

Title: Cloudflare Pages - Cloudflare Workers

Body:
So i started to get my hands dirty with cloudflare pages and workers

My thought is

get a domain mydomain.com (done)

make a static site @ github myaccount.github.io (done)

make a cloudflare pages page add CNAME to DNS ZONE (done) so myaccount.github.io can be @ my-official-site.com (done)

make a cloudflare worker https://myworker.myclaccount.workers.dev (done)

So when i request my-official-site.com i get the content of myaccount.github.io

Now i want to run from my myaccount.github.io a worker to get some html or json or....

I trying to fetch from my myaccount.github.io (index.html)

I get the request to my worker like this

const html =
  "
This markup was generated by a Cloudflare Worker.
"

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})

The problem is

Access to fetch at 'https://myworker.myclaccount.workers.dev/'
from origin 'my-official-site.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I create a

_headers.txt   (https://developers.cloudflare.com/pages/platform/headers) at the root of my github "site" with this

/*
  Access-Control-Allow-Origin: *

but the same...

I'm new to serverless and jamstack (i now js, css, html) but new to this concept

knowledge (android, c#, php, wp, unity, some node.js)

Thank you for your help.

Body:
You don't seem to be using Cloudflare Pages. Such deploy would for the most part replace your current Github Pages + Cloudflare Workers combo, and you wouldn't deal with cross-site requests for the use case you've shown.

Even if you mean to keep using workers as a separate augmentation tool, enabling CORS in your current setup is missing the point. Workers can be transparently mounted on any route of your domain, therefore turning cross-site requests into same-origin even if the real servers are half a planet away.

Anyway, there are for sure several use cases for CORS in workers. For a basic example, here's a simple middleware that takes a Response or a promise of one, returning a copy with modified headers. (There's a lot more to CORS, but that's out of this question's scope)

/**
 * @param {Response|Promise<Response>} res
 * @returns {Promise<Response>}
 */
async function corsEnabler(res) {
   res = await res
   const corsResponse = new Response(res.body, res)
   corsResponse.headers.set('Access-Control-Allow-Origin','*')
   corsResponse.headers.set('Access-Control-Allow-Methods','GET,POST,HEAD,OPTIONS')
   return corsResponse
}

(I'm awaiting res in case I'm passed the promise of a response. But this doesn't mean awaiting for its contents!) Then, where your code says

addEventListener("fetch", event => {
   return event.respondWith(
         handleRequest(event.request)
   )
})

You would use the middleware like

addEventListener("fetch", event => {
   return event.respondWith(
        corsEnabler( handleRequest(event.request) )
   )
})

If you were using module syntax you would use a default export instead of a FetchEvent

export default {
  fetch(request, env, context) {
    return corsEnabler( handleRequest(request) )
  }
}

And if you used page functions:

export async function onRequest(context) {
   return corsEnabler( handleRequest(context.request) )
}


问:
Problem is infeasible with Gurobi, feasible with cbc (but can't access objective value)
I am solving a MILP with cbc and gurobi (via pyomo). Gurobi states that the model is infeasible. As to cbc the solver status states that a feasible and optimal solution is found, but then it fails to access the value of the objective (which in turn crashed my program).

Here is how I access the objective value

```<code>solver_parameters = "ResultFile=model.lp"
opt = SolverFactory(solver)

results = opt.solve(self.model, tee=False, options_string=solver_parameters,logfile="model.log")
# checking status and terminiation condition
print ("The solver returned a status of: "+str(results.solver.status))
print (str(results.solver))
if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition== TerminationCondition.optimal):
   print ("Problem is feasible and solution is optimal")
        objective_value = value(self.model.objective)
else:
   print("Problem is infeasible")
   objective_value = None
</code>```

With cbc I get

```<code>The solver returned a status of: ok

- Status: ok
  Message: CBC 2.10.5
  Termination condition: optimal
  Id: 0
  Error rc: 0
  Time: 0.011972904205322266

Problem is feasible and solution is optimal

ERROR: evaluating object as numeric value: x[0]
        (object: <class 'pyomo.core.base.var._GeneralVarData'>)
    No value for uninitialized NumericValue object x[0]
ERROR: evaluating object as numeric value: objective
        (object: <class 'pyomo.core.base.objective.SimpleObjective'>)
    No value for uninitialized NumericValue object x[0]
Traceback (most recent call last):
...
  File "c:...", line 531, in solve
    objective_value = value(self.model.objective)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 231, in pyomo.core.expr.numvalue.value
  File "C:...\lib\site-packages\pyomo\core\base\expression.py", line 55, in __call__
    return self.expr(exception=exception)
  File "pyomo\core\expr\numeric_expr.pyx", line 218, in pyomo.core.expr.numeric_expr.ExpressionBase.__call__
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 1054, in evaluate_expression
    return visitor.dfs_postorder_stack(exp)
  File "C:...\venv\lib\site-packages\pyomo\core\expr\visitor.py", line 584, in dfs_postorder_stack
    flag, value = self.visiting_potential_leaf(_sub)
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 962, in visiting_potential_leaf
    return True, value(node)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 233, in pyomo.core.expr.numvalue.value
ValueError: No value for uninitialized NumericValue object x[0]
</code>```

On the other hand with gurobi I get

```<code>WARNING: Loading a SolverResults object with a warning status into
    model.name="unknown";
      - termination condition: infeasible
      - message from solver: Model was proven to be infeasible.
The solver returned a status of: warning

- Status: warning
  Return code: 0
  Message: Model was proven to be infeasible.
  Termination condition: infeasible
  Termination message: Model was proven to be infeasible.
  Wall time: 0.0019626617431640625
  Error rc: 0
  Time: 0.08476400375366211

Problem is infeasible
</code>```

I'm assuming problem is indeed infeasible and the error comes from cbc. Is this kind of error common, and what would be a way to avoid this?

Finally, this is the lp model returned by gurobi

```<code>\ Model x79
\ LP format - for model browsing. Use MPS format to capture full model detail.
Maximize
  - 100 x12 - 200 x13 - 300 x14 - 400 x15 - 70 x16 - 140 x17 - 90 x18
   - 90 x19
Subject To
 c_u_x80_: x12 - 100 x1 <= 0
 c_u_x81_: x13 - 100 x2 <= 0
 c_u_x82_: x14 - 100 x3 <= 0
 c_u_x83_: x15 - 100 x4 <= 0
 c_u_x84_: x16 - 50 x5 <= 0
 c_u_x85_: x17 - 50 x6 <= 0
 c_u_x86_: x18 - 25 x7 <= 0
 c_u_x87_: x19 - 25 x8 <= 0
 c_l_x88_: x12 >= 0
 c_l_x89_: x13 >= 0
 c_l_x90_: x14 >= 0
 c_l_x91_: x15 >= 0
 c_l_x92_: x16 >= 0
 c_l_x93_: x17 >= 0
 c_l_x94_: x18 >= 0
 c_l_x95_: x19 >= 0
 c_u_x96_: x1 <= 1
 c_u_x97_: x2 <= 1
 c_u_x98_: x3 <= 1
 c_u_x99_: x4 <= 1
 c_u_x100_: x5 <= 1
 c_u_x101_: x6 <= 1
 c_u_x102_: x7 <= 1
 c_u_x103_: x8 <= 1
 c_e_x104_: x12 + x16 = 51
 c_e_x105_: x13 + x17 = 51
 c_e_x106_: x14 + x18 = 51
 c_e_x107_: x15 + x19 = 51
 c_u_x108_: - x7 + x9 <= 0
 c_u_x109_: - x6 + x10 <= 0
 c_u_x110_: - x2 - x3 + x11 <= 0
 c_u_x111_: x7 - 2 x9 <= 0
 c_u_x112_: x6 - 2 x10 <= 0
 c_u_x113_: x2 + x3 - 2 x11 <= 0
 c_u_x114_: 100 x13 + 20 x14 + 100 x17 + 20 x18 <= 6072
 c_u_x115_: - 20 x18 + 1260 x9 <= 0
 c_u_x116_: - 100 x17 + 1260 x10 <= 0
 c_u_x117_: - 100 x13 - 20 x14 + 1260 x11 <= 0
 c_u_x118_: 2 x1 - x24 <= 0
 c_u_x119_: 2 x2 - x25 <= 0
 c_u_x120_: 15 x3 - x26 <= 0
 c_u_x121_: 10 x4 - x27 <= 0
 c_u_x122_: 1.4 x5 - x24 <= 0
 c_u_x123_: 1.4 x6 - x25 <= 0
 c_u_x124_: 4.5 x7 - x26 <= 0
 c_u_x125_: 2.25 x8 - x27 <= 0
 c_u_x126_: 100 x12 + 200 x13 + 300 x14 + 400 x15 + 70 x16 + 140 x17
   + 90 x18 + 90 x19 - 2550 x24 - 5100 x25 - 1020 x26 - 2040 x27 + 6072 x48
   + 100 x60 + 100 x61 + 100 x62 + 100 x63 + 50 x64 + 50 x65 + 25 x66
   + 25 x67 - 1260 x76 - 1260 x77 - 1260 x78 <= 0
 c_u_x127_: - 1000 x1 + x60 <= 0
 c_u_x128_: - 1000 x2 + x61 <= 0
 c_u_x129_: - 1000 x3 + x62 <= 0
 c_u_x130_: - 1000 x4 + x63 <= 0
 c_u_x131_: - 1000 x5 + x64 <= 0
 c_u_x132_: - 1000 x6 + x65 <= 0
 c_u_x133_: - 1000 x7 + x66 <= 0
 c_u_x134_: - 1000 x8 + x67 <= 0
 c_u_x135_: x60 - x32 <= 0
 c_u_x136_: x61 - x33 <= 0
 c_u_x137_: x62 - x34 <= 0
 c_u_x138_: x63 - x35 <= 0
 c_u_x139_: x64 - x36 <= 0
 c_u_x140_: x65 - x37 <= 0
 c_u_x141_: x66 - x38 <= 0
 c_u_x142_: x67 - x39 <= 0
 c_u_x143_: 1000 x1 - x60 + x32 <= 1000
 c_u_x144_: 1000 x2 - x61 + x33 <= 1000
 c_u_x145_: 1000 x3 - x62 + x34 <= 1000
 c_u_x146_: 1000 x4 - x63 + x35 <= 1000
 c_u_x147_: 1000 x5 - x64 + x36 <= 1000
 c_u_x148_: 1000 x6 - x65 + x37 <= 1000
 c_u_x149_: 1000 x7 - x66 + x38 <= 1000
 c_u_x150_: 1000 x8 - x67 + x39 <= 1000
 c_u_x151_: - 1000 x1 + x68 <= 0
 c_u_x152_: - 1000 x2 + x69 <= 0
 c_u_x153_: - 1000 x3 + x70 <= 0
 c_u_x154_: - 1000 x4 + x71 <= 0
 c_u_x155_: - 1000 x5 + x72 <= 0
 c_u_x156_: - 1000 x6 + x73 <= 0
 c_u_x157_: - 1000 x7 + x74 <= 0
 c_u_x158_: - 1000 x8 + x75 <= 0
 c_u_x159_: x68 - x40 <= 0
 c_u_x160_: x69 - x41 <= 0
 c_u_x161_: x70 - x42 <= 0
 c_u_x162_: x71 - x43 <= 0
 c_u_x163_: x72 - x44 <= 0
 c_u_x164_: x73 - x45 <= 0
 c_u_x165_: x74 - x46 <= 0
 c_u_x166_: x75 - x47 <= 0
 c_u_x167_: 1000 x1 - x68 + x40 <= 1000
 c_u_x168_: 1000 x2 - x69 + x41 <= 1000
 c_u_x169_: 1000 x3 - x70 + x42 <= 1000
 c_u_x170_: 1000 x4 - x71 + x43 <= 1000
 c_u_x171_: 1000 x5 - x72 + x44 <= 1000
 c_u_x172_: 1000 x6 - x73 + x45 <= 1000
 c_u_x173_: 1000 x7 - x74 + x46 <= 1000
 c_u_x174_: 1000 x8 - x75 + x47 <= 1000
 c_u_x175_: - 1000 x9 + x76 <= 0
 c_u_x176_: - 1000 x10 + x77 <= 0
 c_u_x177_: - 1000 x11 + x78 <= 0
 c_u_x178_: x76 - x49 <= 0
 c_u_x179_: x77 - x50 <= 0
 c_u_x180_: x78 - x51 <= 0
 c_u_x181_: 1000 x9 - x76 + x49 <= 1000
 c_u_x182_: 1000 x10 - x77 + x50 <= 1000
 c_u_x183_: 1000 x11 - x78 + x51 <= 1000
 c_l_x184_: - 50 x24 + x32 - x40 >= -100
 c_l_x185_: - 100 x25 + 100 x48 + x33 - x41 - 100 x51 >= -200
 c_l_x186_: - 20 x26 + 20 x48 + x34 - x42 - 20 x51 >= -300
 c_l_x187_: - 40 x27 + x35 - x43 >= -400
 c_l_x188_: - 50 x24 + x36 - x44 >= -70
 c_l_x189_: - 100 x25 + 100 x48 + x37 - x45 - 100 x50 >= -140
 c_l_x190_: - 20 x26 + 20 x48 + x38 - x46 - 20 x49 >= -90
 c_l_x191_: - 40 x27 + x39 - x47 >= -90
 c_u_x192_: x24 <= 2
 c_u_x193_: x25 <= 2
 c_u_x194_: x26 <= 15
 c_u_x195_: x27 <= 10
 c_e_ONE_VAR_CONSTANT: ONE_VAR_CONSTANT = 1
Bounds
 x24 free
 x25 free
 x26 free
 x27 free
Binaries
 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
End
</code>```

答: Try running the model through IIS, which will show what constraints cause the infeasibilities.</p>

Body:
I am solving a MILP with cbc and gurobi (via pyomo). Gurobi states that the model is infeasible. As to cbc the solver status states that a feasible and optimal solution is found, but then it fails to access the value of the objective (which in turn crashed my program).

Here is how I access the objective value

solver_parameters = "ResultFile=model.lp"
opt = SolverFactory(solver)

results = opt.solve(self.model, tee=False, options_string=solver_parameters,logfile="model.log")
# checking status and terminiation condition
print ("The solver returned a status of: "+str(results.solver.status))
print (str(results.solver))
if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition== TerminationCondition.optimal):
   print ("Problem is feasible and solution is optimal")
        objective_value = value(self.model.objective)
else:
   print("Problem is infeasible")
   objective_value = None

With cbc I get

The solver returned a status of: ok

- Status: ok
  Message: CBC 2.10.5
  Termination condition: optimal
  Id: 0
  Error rc: 0
  Time: 0.011972904205322266

Problem is feasible and solution is optimal

ERROR: evaluating object as numeric value: x[0]
        (object: <class 'pyomo.core.base.var._GeneralVarData'>)
    No value for uninitialized NumericValue object x[0]
ERROR: evaluating object as numeric value: objective
        (object: <class 'pyomo.core.base.objective.SimpleObjective'>)
    No value for uninitialized NumericValue object x[0]
Traceback (most recent call last):
...
  File "c:...", line 531, in solve
    objective_value = value(self.model.objective)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 231, in pyomo.core.expr.numvalue.value
  File "C:...\lib\site-packages\pyomo\core\base\expression.py", line 55, in __call__
    return self.expr(exception=exception)
  File "pyomo\core\expr\numeric_expr.pyx", line 218, in pyomo.core.expr.numeric_expr.ExpressionBase.__call__
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 1054, in evaluate_expression
    return visitor.dfs_postorder_stack(exp)
  File "C:...\venv\lib\site-packages\pyomo\core\expr\visitor.py", line 584, in dfs_postorder_stack
    flag, value = self.visiting_potential_leaf(_sub)
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 962, in visiting_potential_leaf
    return True, value(node)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 233, in pyomo.core.expr.numvalue.value
ValueError: No value for uninitialized NumericValue object x[0]

On the other hand with gurobi I get

WARNING: Loading a SolverResults object with a warning status into
    model.name="unknown";
      - termination condition: infeasible
      - message from solver: Model was proven to be infeasible.
The solver returned a status of: warning

- Status: warning
  Return code: 0
  Message: Model was proven to be infeasible.
  Termination condition: infeasible
  Termination message: Model was proven to be infeasible.
  Wall time: 0.0019626617431640625
  Error rc: 0
  Time: 0.08476400375366211

Problem is infeasible

I'm assuming problem is indeed infeasible and the error comes from cbc. Is this kind of error common, and what would be a way to avoid this?

Finally, this is the lp model returned by gurobi

\ Model x79
\ LP format - for model browsing. Use MPS format to capture full model detail.
Maximize
  - 100 x12 - 200 x13 - 300 x14 - 400 x15 - 70 x16 - 140 x17 - 90 x18
   - 90 x19
Subject To
 c_u_x80_: x12 - 100 x1 <= 0
 c_u_x81_: x13 - 100 x2 <= 0
 c_u_x82_: x14 - 100 x3 <= 0
 c_u_x83_: x15 - 100 x4 <= 0
 c_u_x84_: x16 - 50 x5 <= 0
 c_u_x85_: x17 - 50 x6 <= 0
 c_u_x86_: x18 - 25 x7 <= 0
 c_u_x87_: x19 - 25 x8 <= 0
 c_l_x88_: x12 >= 0
 c_l_x89_: x13 >= 0
 c_l_x90_: x14 >= 0
 c_l_x91_: x15 >= 0
 c_l_x92_: x16 >= 0
 c_l_x93_: x17 >= 0
 c_l_x94_: x18 >= 0
 c_l_x95_: x19 >= 0
 c_u_x96_: x1 <= 1
 c_u_x97_: x2 <= 1
 c_u_x98_: x3 <= 1
 c_u_x99_: x4 <= 1
 c_u_x100_: x5 <= 1
 c_u_x101_: x6 <= 1
 c_u_x102_: x7 <= 1
 c_u_x103_: x8 <= 1
 c_e_x104_: x12 + x16 = 51
 c_e_x105_: x13 + x17 = 51
 c_e_x106_: x14 + x18 = 51
 c_e_x107_: x15 + x19 = 51
 c_u_x108_: - x7 + x9 <= 0
 c_u_x109_: - x6 + x10 <= 0
 c_u_x110_: - x2 - x3 + x11 <= 0
 c_u_x111_: x7 - 2 x9 <= 0
 c_u_x112_: x6 - 2 x10 <= 0
 c_u_x113_: x2 + x3 - 2 x11 <= 0
 c_u_x114_: 100 x13 + 20 x14 + 100 x17 + 20 x18 <= 6072
 c_u_x115_: - 20 x18 + 1260 x9 <= 0
 c_u_x116_: - 100 x17 + 1260 x10 <= 0
 c_u_x117_: - 100 x13 - 20 x14 + 1260 x11 <= 0
 c_u_x118_: 2 x1 - x24 <= 0
 c_u_x119_: 2 x2 - x25 <= 0
 c_u_x120_: 15 x3 - x26 <= 0
 c_u_x121_: 10 x4 - x27 <= 0
 c_u_x122_: 1.4 x5 - x24 <= 0
 c_u_x123_: 1.4 x6 - x25 <= 0
 c_u_x124_: 4.5 x7 - x26 <= 0
 c_u_x125_: 2.25 x8 - x27 <= 0
 c_u_x126_: 100 x12 + 200 x13 + 300 x14 + 400 x15 + 70 x16 + 140 x17
   + 90 x18 + 90 x19 - 2550 x24 - 5100 x25 - 1020 x26 - 2040 x27 + 6072 x48
   + 100 x60 + 100 x61 + 100 x62 + 100 x63 + 50 x64 + 50 x65 + 25 x66
   + 25 x67 - 1260 x76 - 1260 x77 - 1260 x78 <= 0
 c_u_x127_: - 1000 x1 + x60 <= 0
 c_u_x128_: - 1000 x2 + x61 <= 0
 c_u_x129_: - 1000 x3 + x62 <= 0
 c_u_x130_: - 1000 x4 + x63 <= 0
 c_u_x131_: - 1000 x5 + x64 <= 0
 c_u_x132_: - 1000 x6 + x65 <= 0
 c_u_x133_: - 1000 x7 + x66 <= 0
 c_u_x134_: - 1000 x8 + x67 <= 0
 c_u_x135_: x60 - x32 <= 0
 c_u_x136_: x61 - x33 <= 0
 c_u_x137_: x62 - x34 <= 0
 c_u_x138_: x63 - x35 <= 0
 c_u_x139_: x64 - x36 <= 0
 c_u_x140_: x65 - x37 <= 0
 c_u_x141_: x66 - x38 <= 0
 c_u_x142_: x67 - x39 <= 0
 c_u_x143_: 1000 x1 - x60 + x32 <= 1000
 c_u_x144_: 1000 x2 - x61 + x33 <= 1000
 c_u_x145_: 1000 x3 - x62 + x34 <= 1000
 c_u_x146_: 1000 x4 - x63 + x35 <= 1000
 c_u_x147_: 1000 x5 - x64 + x36 <= 1000
 c_u_x148_: 1000 x6 - x65 + x37 <= 1000
 c_u_x149_: 1000 x7 - x66 + x38 <= 1000
 c_u_x150_: 1000 x8 - x67 + x39 <= 1000
 c_u_x151_: - 1000 x1 + x68 <= 0
 c_u_x152_: - 1000 x2 + x69 <= 0
 c_u_x153_: - 1000 x3 + x70 <= 0
 c_u_x154_: - 1000 x4 + x71 <= 0
 c_u_x155_: - 1000 x5 + x72 <= 0
 c_u_x156_: - 1000 x6 + x73 <= 0
 c_u_x157_: - 1000 x7 + x74 <= 0
 c_u_x158_: - 1000 x8 + x75 <= 0
 c_u_x159_: x68 - x40 <= 0
 c_u_x160_: x69 - x41 <= 0
 c_u_x161_: x70 - x42 <= 0
 c_u_x162_: x71 - x43 <= 0
 c_u_x163_: x72 - x44 <= 0
 c_u_x164_: x73 - x45 <= 0
 c_u_x165_: x74 - x46 <= 0
 c_u_x166_: x75 - x47 <= 0
 c_u_x167_: 1000 x1 - x68 + x40 <= 1000
 c_u_x168_: 1000 x2 - x69 + x41 <= 1000
 c_u_x169_: 1000 x3 - x70 + x42 <= 1000
 c_u_x170_: 1000 x4 - x71 + x43 <= 1000
 c_u_x171_: 1000 x5 - x72 + x44 <= 1000
 c_u_x172_: 1000 x6 - x73 + x45 <= 1000
 c_u_x173_: 1000 x7 - x74 + x46 <= 1000
 c_u_x174_: 1000 x8 - x75 + x47 <= 1000
 c_u_x175_: - 1000 x9 + x76 <= 0
 c_u_x176_: - 1000 x10 + x77 <= 0
 c_u_x177_: - 1000 x11 + x78 <= 0
 c_u_x178_: x76 - x49 <= 0
 c_u_x179_: x77 - x50 <= 0
 c_u_x180_: x78 - x51 <= 0
 c_u_x181_: 1000 x9 - x76 + x49 <= 1000
 c_u_x182_: 1000 x10 - x77 + x50 <= 1000
 c_u_x183_: 1000 x11 - x78 + x51 <= 1000
 c_l_x184_: - 50 x24 + x32 - x40 >= -100
 c_l_x185_: - 100 x25 + 100 x48 + x33 - x41 - 100 x51 >= -200
 c_l_x186_: - 20 x26 + 20 x48 + x34 - x42 - 20 x51 >= -300
 c_l_x187_: - 40 x27 + x35 - x43 >= -400
 c_l_x188_: - 50 x24 + x36 - x44 >= -70
 c_l_x189_: - 100 x25 + 100 x48 + x37 - x45 - 100 x50 >= -140
 c_l_x190_: - 20 x26 + 20 x48 + x38 - x46 - 20 x49 >= -90
 c_l_x191_: - 40 x27 + x39 - x47 >= -90
 c_u_x192_: x24 <= 2
 c_u_x193_: x25 <= 2
 c_u_x194_: x26 <= 15
 c_u_x195_: x27 <= 10
 c_e_ONE_VAR_CONSTANT: ONE_VAR_CONSTANT = 1
Bounds
 x24 free
 x25 free
 x26 free
 x27 free
Binaries
 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
End


问:
RxJs mergeAll(), scan() coninutes to accumulate
I have this bit of code that is intended to accumulate features as they are added ot the features$$ observable.

```<code>  private features$$: BehaviorSubject<Observable<Feature<FeatureConfig>>> = new BehaviorSubject<
    Observable<Feature<FeatureConfig>>
  >(of());

  private features$: Observable<Feature<FeatureConfig>[]> = this.features$$.pipe(
    mergeAll(),
    scan((acc: Feature<FeatureConfig>[], filter: Feature<FeatureConfig>) => {
      acc.push(filter);
      return acc;
    }, [] as Feature<FeatureConfig>[])
  );

</code>```

The object itself is not important, but they are added with an add function:

```<code>  add(feature: FeatureConfig): void {
    this.features$$.next(
      of({
        key: feature.friendlyId,
        value: feature
      })
    );
  }
</code>```

and then publicly exposed via a an observable that is intended to filture the current features by a value:

```<code>  feature$ = (feature: string): Observable<FeatureConfig | null> => {
    return this.features$.pipe(
      map((features: FeatureConfig[]) => {
        return (
          features.find((featureConfig: FeatureConfig) => {
            return featureConfig.key === feature;
          })?.value ?? null
        );
      })
    );
  };

</code>```

This seems to work fine except every time something calls the feature$(feature: string) it hits the acc.push(filter) line in the private features$ observable scan operator. Perhaps I misunderstood the pattern or how mergeAll/scan behave or I just am missing something obvious? My thought was it should just return the current value of whatever has been pushed to features$$ at any given time?

答:
Add the shareReplay(1) operator after the scan operator where features$ is defined:

```<code>private features$: Observable<Feature<FeatureConfig>[]> = this.features$$.pipe(
  mergeAll(),
  scan((acc: Feature<FeatureConfig>[], filter: Feature<FeatureConfig>) => {
    acc.push(filter);
    return acc;
  }, [] as Feature<FeatureConfig>[]),
  shareReplay(1)
);
</code>```

This will prevent the Observable chain before the shareReplay operator to re-run every time there is a new subscription.

Body:
I have this bit of code that is intended to accumulate features as they are added ot the features$$ observable.

  private features$$: BehaviorSubject<Observable<Feature<FeatureConfig>>> = new BehaviorSubject<
    Observable<Feature<FeatureConfig>>
  >(of());

  private features$: Observable<Feature<FeatureConfig>[]> = this.features$$.pipe(
    mergeAll(),
    scan((acc: Feature<FeatureConfig>[], filter: Feature<FeatureConfig>) => {
      acc.push(filter);
      return acc;
    }, [] as Feature<FeatureConfig>[])
  );

The object itself is not important, but they are added with an add function:

  add(feature: FeatureConfig): void {
    this.features$$.next(
      of({
        key: feature.friendlyId,
        value: feature
      })
    );
  }

and then publicly exposed via a an observable that is intended to filture the current features by a value:

  feature$ = (feature: string): Observable<FeatureConfig | null> => {
    return this.features$.pipe(
      map((features: FeatureConfig[]) => {
        return (
          features.find((featureConfig: FeatureConfig) => {
            return featureConfig.key === feature;
          })?.value ?? null
        );
      })
    );
  };

This seems to work fine except every time something calls the feature$(feature: string) it hits the acc.push(filter) line in the private features$ observable scan operator. Perhaps I misunderstood the pattern or how mergeAll/scan behave or I just am missing something obvious? My thought was it should just return the current value of whatever has been pushed to features$$ at any given time?

Body:
Add the shareReplay(1) operator after the scan operator where features$ is defined:

private features$: Observable<Feature<FeatureConfig>[]> = this.features$$.pipe(
  mergeAll(),
  scan((acc: Feature<FeatureConfig>[], filter: Feature<FeatureConfig>) => {
    acc.push(filter);
    return acc;
  }, [] as Feature<FeatureConfig>[]),
  shareReplay(1)
);

This will prevent the Observable chain before the shareReplay operator to re-run every time there is a new subscription.


问:
Get root, inner, and leaf nodes from a table?
Given a table of nodes (their Ids and their Parent Ids), how can I get all root, inner, and leaf nodes?

Here's what I have so far:

Root Nodes

```<code>SELECT Id, "Root" FROM NodeTable
WHERE ParentId IS NULL;
</code>```

Inner Nodes

```<code>???
</code>```

Leaf Nodes

```<code>SELECT N1.Id, "Leaf" FROM NodeTable N1
LEFT JOIN NodeTable N2 ON N1.Id = N2.ParentId
WHERE N2.ParentId IS NULL;
</code>```

Is this correct? Is there a way I can do this in just one query?

答:
```<code>select N, Case
when P is null then 'Root'
when N in (select P from BST) then 'Inner'
Else 'Leaf' end from BST order by N asc
</code>```

Body:
Given a table of nodes (their Ids and their Parent Ids), how can I get all root, inner, and leaf nodes?

Here's what I have so far:

Root Nodes

SELECT Id, "Root" FROM NodeTable
WHERE ParentId IS NULL;

Inner Nodes

???

Leaf Nodes

SELECT N1.Id, "Leaf" FROM NodeTable N1
LEFT JOIN NodeTable N2 ON N1.Id = N2.ParentId
WHERE N2.ParentId IS NULL;

Is this correct? Is there a way I can do this in just one query?


问:
My fresh Laravel 9 app cannot see a controller
I have a fresh instance of Laravel 9. I am migrating all my controllers from an old Laravel 8 application. My problem is that the app cannot see the controller.

Target class [AdminToolsController] does not exist.

web.php

```<code>Route::get('/php', 'AdminToolsController@php');
</code>```

Controller

```<code>public function php()
{
    $laravel = app();
    echo "Your Laravel version is ".$laravel::VERSION;
    echo phpinfo();
}
</code>```

答:
The syntax for routes has been Route::get(uri, [controller, action]) for some time now. It's not a laravel 9 thing

use App\Http\Controllers\AdminToolsController;

Route::get('/php', [AdminToolsController::class, 'php']);
```
<p>or</p>
<pre class="lang-php prettyprint-override"><code>Route::get('/php', [\App\Http\Controllers\AdminToolsController::class, 'php']);
</code>```

Body:
I have a fresh instance of Laravel 9. I am migrating all my controllers from an old Laravel 8 application. My problem is that the app cannot see the controller.

Target class [AdminToolsController] does not exist.

web.php

Route::get('/php', 'AdminToolsController@php');

Controller

public function php()
{
    $laravel = app();
    echo "Your Laravel version is ".$laravel::VERSION;
    echo phpinfo();
}

Body:
The syntax for routes has been Route::get(uri, [controller, action]) for some time now. It's not a laravel 9 thing

use App\Http\Controllers\AdminToolsController;

Route::get('/php', [AdminToolsController::class, 'php']);

or

Route::get('/php', [\App\Http\Controllers\AdminToolsController::class, 'php']);


问:
Extending react-native-paper components in TypeScript
I'm struggling to extend the react-native-paper components correctly. What am I doing wrong or how to do it correctly? actually, I'm not totally new to Typescript, but I always struggled with this one:

// TextInput.tsx
import React from "react";
import { TextInput as PaperTextInput } from "react-native-paper";
import { TextInputProps } from "react-native-paper/lib/typescript/src/components/TextInput/TextInput";

interface MyTextInputProps extends TextInputProps {}

const MyTextInput: React.FC<MyTextInputProps> = (props) => {
  return <PaperTextInput {...props} />;
};

export default MyTextInput;
```
<pre class="lang-js prettyprint-override"><code>// Usage:
<TextInput mode="outlined" style={styles.input} label="Email" />
</code>```

And I get this error:

Property 'theme' is missing in type '{ mode: "outlined"; style: { alignSelf: "stretch"; }; label: string; }' but required in type 'MyTextInputProps'

答:
You can use defaultProps to set a theme and it should solve the problem.

import React from "react";
import { TextInput as PaperTextInput, DefaultTheme } from "react-native-paper";

interface Props extends TextInputProps {
  yourCustomProperty: string;
}

const MyTextInput = (props : Props) => {
  return <PaperTextInput {...props} />;
};

MyTextInput.defaultProps = {
  theme: DefaultTheme
}

export default MyTextInput;
```

Body:
I'm struggling to extend the react-native-paper components correctly. What am I doing wrong or how to do it correctly? actually, I'm not totally new to Typescript, but I always struggled with this one:

// TextInput.tsx
import React from "react";
import { TextInput as PaperTextInput } from "react-native-paper";
import { TextInputProps } from "react-native-paper/lib/typescript/src/components/TextInput/TextInput";

interface MyTextInputProps extends TextInputProps {}

const MyTextInput: React.FC<MyTextInputProps> = (props) => {
  return <PaperTextInput {...props} />;
};

export default MyTextInput;

// Usage:
<TextInput mode="outlined" style={styles.input} label="Email" />

And I get this error:

Property 'theme' is missing in type '{ mode: "outlined"; style: { alignSelf: "stretch"; }; label: string; }' but required in type 'MyTextInputProps'


问:
Pairing list elements with indexes
Given a list of elements, I need to turn each element into a pair of the index number and the element. There are several ways to do it; this is the most concise I have found so far:

```<code>List.mapi (fun i x->i,x) xs
</code>```

But is there a more concise/idiomatic way to do it? For example, does F# have some built-in function to turn two elements into a pair, some equivalent of the C++ make_pair?

答: There is a function in the standard library that does exactly that: List.indexed

Title: Pairing list elements with indexes

Body:
Given a list of elements, I need to turn each element into a pair of the index number and the element. There are several ways to do it; this is the most concise I have found so far:

List.mapi (fun i x->i,x) xs

But is there a more concise/idiomatic way to do it? For example, does F# have some built-in function to turn two elements into a pair, some equivalent of the C++ make_pair?


答:
Say, you have a field _speed and you want to set it using inspector. It means we want it to be serialized - stored somewhere in a human-readable and flexible format(e.g. xml), not directly in code. So when you edit fields in inspector, you edit the serialized data. During compilation, it's being deserialized and assigned to a field. This is how serialization/desearialization works. It is used to store non-static or just big amounts of data. In case of Unity it is used to show you everything in inspector. Transform has position and scale variables serialized and you can edit them.

In Unity there are two common ways to make fields assignable in inspector: using public fields or using [SerializedField] attribute for private ones.

Making fields public just to edit them with inspector is bad practice. If you can edit field in inspector, it means every other component can too, which is insecure. There is no good architecture that allows such things. If you want other components to edit the field, make it a property or make a set method. If you just need to assign fields by hand, don't use public fields. Avoid them.

When you use the [SerializeField] attribute, you create a private field that is accessible to this component only and you can assign it in inspector at the same time. If you need other components to read it, you can make a public property without set (public float Speed => _speed;).

This all is not an obligatory usage. Just good practice.

Title: What do people mean when they talk about serialization in Unity?

Body:
I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using

[SerializeField]

and don't know why or what it does.


问:
Maxlength for input type number
I have a number input field in HTML.

```<code>  <input type="number" value="0">
</code>```

and I'd like for the user to not be able to type more than five characters into the textbox.

I've used the maxlength attribute before when the type is set to text, but that doesn't work with the number attribute. Is there a relatively simple solution (inline HTML is preferred) to overcome this and limit the number of characters?

Thanks.

答:
If you want a maximum of 5 digits in the number, you can use the largest 5 digit number and set that as the max attribute for the input:

<input type="number" max="99999" />
```
<p>The above will only maximize the number to <code>99999</code>, but will not disallow input of more than 5 characters. This can't be done with HTML alone.</p>
<p>It can, though, be done with JavaScript. For example:</p>
<pre class="lang-html prettyprint-override"><code><input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type="number"
    maxlength="5"
 />
</code>```

All the code above does is, oninput, it checks the number of characters in the input, and if that is exceeding the number of characters specified in maxlength, it deletes the character.

Source: maxlength ignored for input type="number" in Chrome

Title: Maxlength for input type number

Body:
I have a number input field in HTML.

  <input type="number" value="0">

and I'd like for the user to not be able to type more than five characters into the textbox.

I've used the maxlength attribute before when the type is set to text, but that doesn't work with the number attribute. Is there a relatively simple solution (inline HTML is preferred) to overcome this and limit the number of characters?

Thanks.

Body:
If you want a maximum of 5 digits in the number, you can use the largest 5 digit number and set that as the max attribute for the input:

<input type="number" max="99999" />

The above will only maximize the number to 99999, but will not disallow input of more than 5 characters. This can't be done with HTML alone.

It can, though, be done with JavaScript. For example:

<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type="number"
    maxlength="5"
 />

All the code above does is, oninput, it checks the number of characters in the input, and if that is exceeding the number of characters specified in maxlength, it deletes the character.

Source: maxlength ignored for input type="number" in Chrome