问:
SQL: SUM on Aggregate columns
I have this query:

```<code>SELECT
  spend_codes.spend_code,
  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
FROM spend_codeables
LEFT JOIN spend_codes
  ON spend_codeables.spend_code_id = spend_codes.id
LEFT JOIN orders
  ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
LEFT JOIN ordered_items
  ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
GROUP BY
  spend_codes.spend_code;
</code>```

Which has this result:

```<code>+--------------+---------------+--------------+
| spend_code   | order_total   | item_total   |
|--------------+---------------+--------------|
| 1230131391   | $362.00       | <null>       |
| A12345       | <null>        | <null>       |
| B29393       | <null>        | $374.28      |
+--------------+---------------+--------------+
</code>```

However, I'd like to add order_total and item_total in order to get just total.

So I'd expect this:

```<code>+--------------+---------------+
| spend_code   | total         |
|--------------+---------------+
| 1230131391   | $362.00       |
| A12345       | <null>        |
| B29393       | $374.28       |
+--------------+---------------+
</code>```

Doing this did not work:

```<code>  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) +
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as total

</code>```

Another monkeywrench is that the type of the numbers is money not integer.

Anyone would be able to help?

答:
you do it in next step using sub query and I used coalesce() for avoid null</p>
```<code>   with cte as ( SELECT
      spend_codes.spend_code,
      SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
      SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
    FROM spend_codeables
    LEFT JOIN spend_codes
      ON spend_codeables.spend_code_id = spend_codes.id
    LEFT JOIN orders
      ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
    LEFT JOIN ordered_items
      ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
    GROUP BY
      spend_codes.spend_code
) select spend_code,coalesce(order_total,0)+coalesce(item_total,0) as total from cte
</code>```

Title: SQL: SUM on Aggregate columns

Body:
I have this query:

SELECT
  spend_codes.spend_code,
  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
FROM spend_codeables
LEFT JOIN spend_codes
  ON spend_codeables.spend_code_id = spend_codes.id
LEFT JOIN orders
  ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
LEFT JOIN ordered_items
  ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
GROUP BY
  spend_codes.spend_code;

Which has this result:

+--------------+---------------+--------------+
| spend_code   | order_total   | item_total   |
|--------------+---------------+--------------|
| 1230131391   | $362.00       | <null>       |
| A12345       | <null>        | <null>       |
| B29393       | <null>        | $374.28      |
+--------------+---------------+--------------+

However, I'd like to add order_total and item_total in order to get just total.

So I'd expect this:

+--------------+---------------+
| spend_code   | total         |
|--------------+---------------+
| 1230131391   | $362.00       |
| A12345       | <null>        |
| B29393       | $374.28       |
+--------------+---------------+

Doing this did not work:

  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) +
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as total

Another monkeywrench is that the type of the numbers is money not integer.

Anyone would be able to help?

Body:
you do it in next step using sub query and I used coalesce() for avoid null

   with cte as ( SELECT
      spend_codes.spend_code,
      SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
      SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
    FROM spend_codeables
    LEFT JOIN spend_codes
      ON spend_codeables.spend_code_id = spend_codes.id
    LEFT JOIN orders
      ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
    LEFT JOIN ordered_items
      ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
    GROUP BY
      spend_codes.spend_code
) select spend_code,coalesce(order_total,0)+coalesce(item_total,0) as total from cte


来源: stackexchange

问:
Regex to find content of the last occurence of square brackets
Hi Everybody,

I'm Currently using preg_match and I'm trying to extract some informations enclosed in square brackets.

So far, I have used this:

/\[(.*)\]/

But I want it to be only the content of the last occurence - or the first one, if starting from the end!

In the following:

string = "Some text here [value_a] some more text [value_b]"

I need to get:

"value_b"

Can anybody suggest something that will do the trick?

Thanks!

答:
\[([^\]]*)\][^\[]*$

See it here on regexr

```<code>var someText="Some text here [value_a] some more text [value_b]";
alert(someText.match(/\[([^\]]*)\][^\[]*$/)[1]);
</code>```

The part inside the brackets is stored in capture group 1, therefor you need to use match()1 to access the result.

For simple brakets, see the source to make this answer: Regex for getting text between the last brackets ()

ContentLicense: CC BY-SA 3.0

Body:
\[([^\]]*)\][^\[]*$

See it here on regexr

var someText="Some text here [value_a] some more text [value_b]";
alert(someText.match(/\[([^\]]*)\][^\[]*$/)[1]);

The part inside the brackets is stored in capture group 1, therefor you need to use match()1 to access the result.

For simple brakets, see the source to make this answer: Regex for getting text between the last brackets ()

ContentLicense: CC BY-SA 4.0


问:
The activity activityId could not be found (Parameter 'activityId')
For workitems i make
/appbundles = "NamiliftActivity" and appbundles/:id/aliases "beta"

but while sending data on /workitems

axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/da/us-east/v3/workitems',
        headers: {
            'Authorization': 'Bearer ******',
            'content-type': 'application/json'
        },
        data: JSON.stringify({
        activityId: 'BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta',
        arguments: {
          InventorDoc: {
             url: 'https://developer.api.autodesk.com/oss/v2/signedresources/1a2ac1d9-a8af-4aa2-b9d1-8b0fde21bcf3?region=US',
             pathInZip: 'MasterAssembly.iam'
          },
          InventorParams: {
            url: 'data:application/json,{"ProjectNumber":"12345","ProjectName":"8000-2016","PreparedBy":"Nami","DrawingNumber":"Nami","CommissionNumber":"","ElevatorDesignation":"","ElevatorNumber":"","Logo":"NamiLift","LanguageOptions":"ENG","Standard":"PL400","NumberOfFloor":2,"LengthOfCar":2000,"WidthOfCar":1100,"Pits":true,"PitHeight":50,"ZoneSectionStart":239,"HeightAboveTopElevator":0,"ElectricBoxSide":"a","ElectricBoxFloorNo":"0","ElectricBoxDefault":false,"OuterRoof":false,"OuterRoofSide":"A","WindowsSectionA":"0-0","WindowsSectionB":"0-5000","WindowsSectionC":"0-0","WindowsSectionD":"0-0","DefaultDoorSize":false,"Colorelevator":"RAL 9001","Colordoor":"RAL 9001","Safelinemx2":false,"Safelinemx2gsm":false,"Schoolcontrolassa":false,"Schoolcontrol":false,"Intercom":false,"Callsend":false,"Firealarmdrive":false,"Folderseat":false,"Floorvoiceannouncement":false,"Lsfcable":false,"Telephone":false,"Keyswitch":false,"Ups":false,"Comments":"-","LiftHeightLevel0":0,"DoorSideLevel0":"A","TypeOfDoorLevel0":"A1","DoorHingeLevel0":"Right","DoorSizeLevel0":900,"DoorHeightLevel0":2000,"DoorCloserLevel0":true,"CanopyLevel0":true,"CallBoxLevel0":true,"LiftHeightLevel1":5000,"DoorSideLevel1":"A","TypeOfDoorLevel1":"A1","DoorHingeLevel1":"Right","DoorSizeLevel1":900,"DoorHeightLevel1":2000,"DoorCloserLevel1":false,"CanopyLevel1":false,"CallBoxLevel1":false}',
            OutputPDF: 'OutputPDF': {
                    'url': fileName.resultZipUrl,
                    'headers': {
                        'Authorization': 'Bearer ' + values.access_token,
                        'Content-type': 'application/octet-stream'
                    },
                    'verb': 'put'
            },
            onComplete: 'onComplete': {
                    'verb': 'post',
                    'url': config.credentials.callback_url +'/api/forge/datamanagement/signanddownload'
            }
       }
    }
})
```
<p>I am getting this <em><strong>ERROR</strong></em>
<img src="https://i.stack.imgur.com/71L30.png" alt="The activity BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta could not be found (Parameter 'activityId')" /></p>
```The activity BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta could not be found (Parameter 'activityId')
```

And appbundles id already set for workItems

da-manager.autodesk

This is /aliases for finding that particular beta activity

答:
Activity and Appbundles are 2 different concepts / entities. You have named your AppBundle NamiliftActivity, which is not an issue. You can name it anything as long as it uses allowed characters.

The error you have:

The activity BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta could not be found (Parameter 'activityId')

is exactly what it says. There is no such Activity NamiliftActivity with an alias beta. Or is there? Your post only shows an AppBundle with that name+alias.

Body:
For workitems i make
/appbundles = "NamiliftActivity" and appbundles/:id/aliases "beta"

but while sending data on /workitems

axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/da/us-east/v3/workitems',
        headers: {
            'Authorization': 'Bearer ******',
            'content-type': 'application/json'
        },
        data: JSON.stringify({
        activityId: 'BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta',
        arguments: {
          InventorDoc: {
             url: 'https://developer.api.autodesk.com/oss/v2/signedresources/1a2ac1d9-a8af-4aa2-b9d1-8b0fde21bcf3?region=US',
             pathInZip: 'MasterAssembly.iam'
          },
          InventorParams: {
            url: 'data:application/json,{"ProjectNumber":"12345","ProjectName":"8000-2016","PreparedBy":"Nami","DrawingNumber":"Nami","CommissionNumber":"","ElevatorDesignation":"","ElevatorNumber":"","Logo":"NamiLift","LanguageOptions":"ENG","Standard":"PL400","NumberOfFloor":2,"LengthOfCar":2000,"WidthOfCar":1100,"Pits":true,"PitHeight":50,"ZoneSectionStart":239,"HeightAboveTopElevator":0,"ElectricBoxSide":"a","ElectricBoxFloorNo":"0","ElectricBoxDefault":false,"OuterRoof":false,"OuterRoofSide":"A","WindowsSectionA":"0-0","WindowsSectionB":"0-5000","WindowsSectionC":"0-0","WindowsSectionD":"0-0","DefaultDoorSize":false,"Colorelevator":"RAL 9001","Colordoor":"RAL 9001","Safelinemx2":false,"Safelinemx2gsm":false,"Schoolcontrolassa":false,"Schoolcontrol":false,"Intercom":false,"Callsend":false,"Firealarmdrive":false,"Folderseat":false,"Floorvoiceannouncement":false,"Lsfcable":false,"Telephone":false,"Keyswitch":false,"Ups":false,"Comments":"-","LiftHeightLevel0":0,"DoorSideLevel0":"A","TypeOfDoorLevel0":"A1","DoorHingeLevel0":"Right","DoorSizeLevel0":900,"DoorHeightLevel0":2000,"DoorCloserLevel0":true,"CanopyLevel0":true,"CallBoxLevel0":true,"LiftHeightLevel1":5000,"DoorSideLevel1":"A","TypeOfDoorLevel1":"A1","DoorHingeLevel1":"Right","DoorSizeLevel1":900,"DoorHeightLevel1":2000,"DoorCloserLevel1":false,"CanopyLevel1":false,"CallBoxLevel1":false}',
            OutputPDF: 'OutputPDF': {
                    'url': fileName.resultZipUrl,
                    'headers': {
                        'Authorization': 'Bearer ' + values.access_token,
                        'Content-type': 'application/octet-stream'
                    },
                    'verb': 'put'
            },
            onComplete: 'onComplete': {
                    'verb': 'post',
                    'url': config.credentials.callback_url +'/api/forge/datamanagement/signanddownload'
            }
       }
    }
})

I am getting this ERROR

The activity BAsBRLiyiaHR1X9eYiAI4ATPmdcuZ5Pf.NamiliftActivity+beta could not be found (Parameter 'activityId')

And appbundles id already set for workItems

da-manager.autodesk

This is /aliases for finding that particular beta activity


问:
SQLAlchemy Multiple Where Condition
I have an Orders table. And I want to write a query to this table with more than one condition. For example, I want to get an order with id field 1 and order_status  field 3.

Is there a way to do this with SQL Alchemy?

P.S. I am able to check only one condition with the following query.

order = Orders.query.filter_by(restaurant_id = restaurant_id).all()

答:
There are multiple ways of doing this for example if you want to apply an and operation you can simply use filter chain as below

```<code>order = Orders.query.filter(restaurant_id = restaurant_id).filter(id = 1).filter(order_status = "Status").all()
</code>```

You can also use and_ and or_ to apply respective conditions like below.

```<code>cond = and_(restaurant_id = restaurant_id, id = 1)
order = Orders.query.filter(or_(cond, order_status = "Status")).all()
</code>```

Title: SQLAlchemy Multiple Where Condition

Body:
There are multiple ways of doing this for example if you want to apply an and operation you can simply use filter chain as below

order = Orders.query.filter(restaurant_id = restaurant_id).filter(id = 1).filter(order_status = "Status").all()

You can also use and_ and or_ to apply respective conditions like below.

cond = and_(restaurant_id = restaurant_id, id = 1)
order = Orders.query.filter(or_(cond, order_status = "Status")).all()


问:
Compare two Dictionary Key Values
```<code>Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

for key in Roles_dict1.keys():
            Z = [b for b in Roles_dict1.keys() if any(b in a for a in User_list.values())]
print(Z)
</code>```

I'm trying to print Z in the order of Roles_dict1

I'm getting this following as output

['CEO', 'CTO', 'Devops']

Expected output

```<code>{'Jhon':'CEO','Bill':'CTO','MATEW':'Devops'}
</code>```

Thanks in Advance

答: You don't need the first dict for the desired output, as it is equal to User_list.

Title: Compare two Dictionary Key Values

Body:
Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

for key in Roles_dict1.keys():
            Z = [b for b in Roles_dict1.keys() if any(b in a for a in User_list.values())]
print(Z)

I'm trying to print Z in the order of Roles_dict1

I'm getting this following as output

['CEO', 'CTO', 'Devops']

Expected output

{'Jhon':'CEO','Bill':'CTO','MATEW':'Devops'}

Thanks in Advance


问:
Problem looping through web controls
I've got a web page where I am dynamically creating controls during Page_Load event (this is done so because I do not know how many controls I will need until session is active and certain variables are accessible)

I need to be able to loop through these controls to find Checkbox when a button click is processed. Looping through the Form.Controls does not appear to be sufficient. I would think that Request.Form might work but it does not appear to be accessible in my C# block?

What should code for Request.Form look like? OR

Has anyone done this before with dynamically created controls?

Any insight is appreciated.

答:
Since the controls might be nested in other controls, you need to search recursively. You can use this method to find the control:

```<code> public Control FindControlRecursive(Control root, string id)
 {
     if (root.ID == id)
     {
         return root;
     }

     foreach (Control c in root.Controls)
     {
         Control t = FindControlRecursive(c, id);
         if (t != null)
         {
             return t;
         }
     }

     return null;
 }
</code>```

And you can implement it this way:

```<code>CheckBox check = FindControlRecursive(Page.Form, "CheckBox1");
</code>```

Title: Problem looping through web controls

Body:
Since the controls might be nested in other controls, you need to search recursively. You can use this method to find the control:

 public Control FindControlRecursive(Control root, string id)
 {
     if (root.ID == id)
     {
         return root;
     }

     foreach (Control c in root.Controls)
     {
         Control t = FindControlRecursive(c, id);
         if (t != null)
         {
             return t;
         }
     }

     return null;
 }

And you can implement it this way:

CheckBox check = FindControlRecursive(Page.Form, "CheckBox1");


问:
Instance of the injected service is undefined in Angular 12
Angular Version : 12.0.1

I have created a service for a component, My requirement is to use the service only with this component for now. When I inject the service in the component and try to access its instance it is undefined. For the very first time in the ngOnInit, it is acccessible, but undefined elsewhere.

Relevant code in the component :

```<code>@Component({
  selector: 'app-component',
  templateUrl: './app-component.component.html',
  styleUrls: ['./app-component.component.scss'],
  providers : [MyService]
})
export class AppComponent implements OnInit {
  ...some declarations and initializations
  constructor(private myService: MyService) {}

  ngOnInit(): void {
    this.myObservable$ = this.myService?.getSomething('/');
  }

  functionCalledFromTemplaceButtonClick(item : any){

   // The service is undefined here
   return this.myService.getSomething(item);
  }

}
</code>```

Relevant code from the service:

```<code>@Injectable({
  providedIn: 'root',
})
export class MyService {
  constructor(
    private httpClient: HttpClient,
  ) {}

  getSomething(item: any) {
   // Makes an api call here
  }
}
</code>```

I have provided the Service - MyService in the module as well.

None of the existing issues helped, Kindly request for some help.

答:
I removed the method i had and replace it with a arrow function and declared and defined at the top such as below :</p>
```<code>public functionCalledFromTemplaceButtonClick =(item : any) =>{

   // The service has the context here
   return this.myService.getSomething(item);
  }
</code>```

Body:
Angular Version : 12.0.1

I have created a service for a component, My requirement is to use the service only with this component for now. When I inject the service in the component and try to access its instance it is undefined. For the very first time in the ngOnInit, it is acccessible, but undefined elsewhere.

Relevant code in the component :

@Component({
  selector: 'app-component',
  templateUrl: './app-component.component.html',
  styleUrls: ['./app-component.component.scss'],
  providers : [MyService]
})
export class AppComponent implements OnInit {
  ...some declarations and initializations
  constructor(private myService: MyService) {}

  ngOnInit(): void {
    this.myObservable$ = this.myService?.getSomething('/');
  }

  functionCalledFromTemplaceButtonClick(item : any){

   // The service is undefined here
   return this.myService.getSomething(item);
  }

}

Relevant code from the service:

@Injectable({
  providedIn: 'root',
})
export class MyService {
  constructor(
    private httpClient: HttpClient,
  ) {}

  getSomething(item: any) {
   // Makes an api call here
  }
}

I have provided the Service - MyService in the module as well.

None of the existing issues helped, Kindly request for some help.

Body:
I removed the method i had and replace it with a arrow function and declared and defined at the top such as below :

public functionCalledFromTemplaceButtonClick =(item : any) =>{

   // The service has the context here
   return this.myService.getSomething(item);
  }


问:
AppEngine error message on Flask Web Application
I'm implementing a Flask web application (that it's running locally on Python 3.1) on Google's App Engine (Python 3.7) and getting the following error:

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

That's the error log:

```<code>{
  "textPayload": "Traceback (most recent call last):\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2447, in wsgi_app\n    response = self.full_dispatch_request()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1953, in full_dispatch_request\n    return self.finalize_request(rv)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1970, in finalize_request\n    response = self.process_response(response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2269, in process_response\n    self.session_interface.save_session(self, ctx.session, response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask_session/sessions.py\", line 354, in save_session\n    total_seconds(app.permanent_session_lifetime))\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 224, in set\n    self._prune()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 159, in _prune\n    if self._over_threshold():\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 102, in _over_threshold\n    return self._threshold != 0 and self._file_count > self._threshold\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 69, in _file_count\n    return self.get(self._fs_count_file) or 0\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 193, in get\n    pickle_time = self.serializer.load(f)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/serializers.py\", line 29, in load\n    data = pickle.load(f)\nValueError: unsupported pickle protocol: 5",
  "insertId": "62069f77000ddb77156b638a",
  "resource": {
    "type": "gae_app",
    "labels": {
      "version_id": "{VERSION_ID}",
      "module_id": "default",
      "project_id": "{PROJECT_ID",
      "zone": "{ZONE}
    }
  },
  "timestamp": "{DATE}",
  "severity": "ERROR",
  "labels": {
    "clone_id": "00c61b117ccbf120db0bbf309ad2da98e7fc043e3476b10e04eb7dec8eacd8a8fff7a965420d11f752ea4b643abc9f95f12446cbbacbd7d3c1bdefcc1a1f8e9445f4a6d8b98de1d3fe4073120f2464989ace693a"
  },
  "logName": "projects/{PROJECT_NAME}/logs/stderr",
  "receiveTimestamp": "{DATE}"
}
</code>```

答:
it says ValueError: unsupported pickle protocol: 5, so probably you need to install python pickle5?

Install pickle5 on your system:

```<code>pip install pickle5
</code>```

import pickle5 instead of pickle in your code:

```<code>import pickle5 as pickle
</code>```

Body:
I'm implementing a Flask web application (that it's running locally on Python 3.1) on Google's App Engine (Python 3.7) and getting the following error:

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

That's the error log:

{
  "textPayload": "Traceback (most recent call last):\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2447, in wsgi_app\n    response = self.full_dispatch_request()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1953, in full_dispatch_request\n    return self.finalize_request(rv)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 1970, in finalize_request\n    response = self.process_response(response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py\", line 2269, in process_response\n    self.session_interface.save_session(self, ctx.session, response)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/flask_session/sessions.py\", line 354, in save_session\n    total_seconds(app.permanent_session_lifetime))\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 224, in set\n    self._prune()\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 159, in _prune\n    if self._over_threshold():\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 102, in _over_threshold\n    return self._threshold != 0 and self._file_count > self._threshold\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 69, in _file_count\n    return self.get(self._fs_count_file) or 0\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/file.py\", line 193, in get\n    pickle_time = self.serializer.load(f)\n  File \"/layers/google.python.pip/pip/lib/python3.7/site-packages/cachelib/serializers.py\", line 29, in load\n    data = pickle.load(f)\nValueError: unsupported pickle protocol: 5",
  "insertId": "62069f77000ddb77156b638a",
  "resource": {
    "type": "gae_app",
    "labels": {
      "version_id": "{VERSION_ID}",
      "module_id": "default",
      "project_id": "{PROJECT_ID",
      "zone": "{ZONE}
    }
  },
  "timestamp": "{DATE}",
  "severity": "ERROR",
  "labels": {
    "clone_id": "00c61b117ccbf120db0bbf309ad2da98e7fc043e3476b10e04eb7dec8eacd8a8fff7a965420d11f752ea4b643abc9f95f12446cbbacbd7d3c1bdefcc1a1f8e9445f4a6d8b98de1d3fe4073120f2464989ace693a"
  },
  "logName": "projects/{PROJECT_NAME}/logs/stderr",
  "receiveTimestamp": "{DATE}"
}

Body:
it says ValueError: unsupported pickle protocol: 5, so probably you need to install python pickle5?

Install pickle5 on your system:

pip install pickle5

import pickle5 instead of pickle in your code:

import pickle5 as pickle


问:
Connection Logint to dashboard (Not detect the passwords)
Please check my code and tell me how to make it when click submits button, it goes to a dashboard page. but it does not work. Help.. I think functions not working. I can't figure out what is the problem. I already create my database and I added details in that database.

(I add database and) I will attach GitHub link too. Please check if you have time.

https://github.com/Dushan26/my_assignment.git

```<code><?php

$host="localhost";
$user="root";
$password="";
$db="project_db";

$connect_error = 'Sorry, we\'re experiencing connection issues.';
$con=mysqli_connect($host,$user,$password);
mysqli_select_db($con, 'project_db') or die(mysqli_error($con));

if(isset($_POST['username'])){

    $uname=$_POST['txtUsername'];
    $password=$_POST['txtPassword'];

    $sql="select * from user where email='".$uname."'AND password='".$password."' limit 1";

    $result=mysql_query($sql);

    if(mysql_num_rows($result)==1){
        echo " You Have Successfully Logged in";
        exit();
    }
    else{
        echo " You Have Entered Incorrect Password";
        exit();
    }

}
?>

<html>
    <head>
        <title>Online class</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

        <style>
            body{
                width: 100%;
                height: 400px;
                background-image:url(../assets/img/online-class.png);
                background-size: cover;
            }</style>

    </head>
    <body>
        <div class="container">
            <div class="row"><!--row 01-->
                <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"><!--row 02-->
                    <div class="card my-5"> <!-- card-->
                        <div class="card-body"><!--card body-->

                            <h5 class="text-center my-2"><b>:::LOGIN:::</h5></b><br>
                        <form class="form" action="" role="form" method="POST">

                            <div clss="my-5" id="divEmail"><!--txtusername-->
                            <input type="text" id="email" name="txtUsername" class="form-control" placeholder="Enter Email">
                            </div><!--end oftxtusername--><br>

                            <div clss="my-5" id="divPassword"><!-- password-->
                            <input type="password" id="password" name="txtPassword" class="form-control" placeholder="Enter Password">
                            </div><!--end of password--><br>

                            <div clss="my-4"><!-- button-->
                            <button type="submit" id="btnSubmit" class="btn btn-danger btn-block text-uppercase col-12">Submit</button>
                            </div><!--end of button-->

                            <hr class="my-4"><h6>Enter Your Email & Password</h6>

                        </form><!--end of form-->

                </div><!--end of card body-->
                </div><!--end of card-->
            </div><!--end row 02-->

        </div><!--end of row 01-->
    </div><!--end of container-->

</code>```

答:
I think your submit button is a type of a "submit". when it is inside a form and clicked, by default it submit the form regardless of your click function.

you can change the button type to "button" or change the click function to stop the form submit

```<code>$("form").submit(function (e) {
    e.preventDefault();
    // your code here
});
</code>```

Body:
Please check my code and tell me how to make it when click submits button, it goes to a dashboard page. but it does not work. Help.. I think functions not working. I can't figure out what is the problem. I already create my database and I added details in that database.

(I add database and) I will attach GitHub link too. Please check if you have time.

https://github.com/Dushan26/my_assignment.git

<?php

$host="localhost";
$user="root";
$password="";
$db="project_db";

$connect_error = 'Sorry, we\'re experiencing connection issues.';
$con=mysqli_connect($host,$user,$password);
mysqli_select_db($con, 'project_db') or die(mysqli_error($con));

if(isset($_POST['username'])){

    $uname=$_POST['txtUsername'];
    $password=$_POST['txtPassword'];

    $sql="select * from user where email='".$uname."'AND password='".$password."' limit 1";

    $result=mysql_query($sql);

    if(mysql_num_rows($result)==1){
        echo " You Have Successfully Logged in";
        exit();
    }
    else{
        echo " You Have Entered Incorrect Password";
        exit();
    }

}
?>

        <title>Online class</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

:::LOGIN:::

                        <form class="form" action="" role="form" method="POST">

                            <input type="text" id="email" name="txtUsername" class="form-control" placeholder="Enter Email">

                            <input type="password" id="password" name="txtPassword" class="form-control" placeholder="Enter Password">

                            <button type="submit" id="btnSubmit" class="btn btn-danger btn-block text-uppercase col-12">Submit</button>

Enter Your Email & Password

                        </form>

Body:
I think your submit button is a type of a "submit". when it is inside a form and clicked, by default it submit the form regardless of your click function.

you can change the button type to "button" or change the click function to stop the form submit

$("form").submit(function (e) {
    e.preventDefault();
    // your code here
});


问:
How to subtract Yesterday count by today count when there is mutual items in power bi?
I want to code like this in dax :

答:
You can do this using variable inside measure.
Here example

```<code>Count = var _selectedday = SELECTEDVALUE('Table'[Date])
var _AccYesterday = CALCULATETABLE(VALUES('Table'[Account]),'Table'[Date] = _selectedday-1)
return
CALCULATE( COUNTROWS(VALUES('Table'[Account])), NOT('Table'[Account] in _AccYesterday))
</code>```

Body: I want to code like this in dax :

Body:
You can do this using variable inside measure.
Here example

Count = var _selectedday = SELECTEDVALUE('Table'[Date])
var _AccYesterday = CALCULATETABLE(VALUES('Table'[Account]),'Table'[Date] = _selectedday-1)
return
CALCULATE( COUNTROWS(VALUES('Table'[Account])), NOT('Table'[Account] in _AccYesterday))


问:
Registering COM objects on Windows 7
I am running Visual Studio in none administrative mode under Windows 7. Everything works well except for the COM registration every time i build my project. Does anyone know how to solve this?</p>

答: Right-click on Visual Studio and choose "Run as administrator" when starting it.</p>

Title: Registering COM objects on Windows 7


问:
Css module in ReactJS, using in ternary operators syntax
I have a useState and try to render my Modal windows based on it.
Here is my code and I used css modules for my classes.
The thing is I am not able to find the correct syntax to doing so.
I ended up writing this but it does not work.</p>
```<code>export default function Modal({ content }) {
  const [showModal, setShowModal] = useState(true);

  return (
    <div className={`${showModal} ? ${styles.ModalWindow} : ${styles.DisplayNone}`} </div>
</code>```

答:
The backtick (`) symbol indicates a template literal/string in JavaScript. You would only want to use this feature if you want the class to literally be something like "condition ? window-class : hidden".

In this case, you want the expression to be evaluated, not converted into a string literal. So just get rid of those template literal markers:

```<code><div className={showModal ? styles.ModalWindow : styles.DisplayNone} </div>
</code>```

Body:
I have a useState and try to render my Modal windows based on it.
Here is my code and I used css modules for my classes.
The thing is I am not able to find the correct syntax to doing so.
I ended up writing this but it does not work.

export default function Modal({ content }) {
  const [showModal, setShowModal] = useState(true);

  return (
    <div className={`${showModal} ? ${styles.ModalWindow} : ${styles.DisplayNone}`}

Body:
The backtick (`) symbol indicates a template literal/string in JavaScript. You would only want to use this feature if you want the class to literally be something like "condition ? window-class : hidden".

In this case, you want the expression to be evaluated, not converted into a string literal. So just get rid of those template literal markers:

<div className={showModal ? styles.ModalWindow : styles.DisplayNone} </div>


问:
azure APIM I need hide section Authorization in portal developer operation details
We did a new release of the development portal in the Azure API Management and it showed the following message:

Creating a new revision or changing revisions will automatically update the portal to the latest version of the software. Content saved in the administrative version of the portal will not be changed.

Which caused that in my portal it now shows me in the box in the transaction detail section all the information to request the authorization token with oauth 2.0

How can I hide the authorization element so that it does not show in my portal for security reasons?

答:
The new Authorization section in the API reference pages surfaces only public information required for clients to authenticate against your API. It doesn't show the secret configuration of your OAuth server. This information has always been publicly accessible, now we just visually render it. If, for some reason, you need to hide the public OAuth server details, you can remove the authorization server configuration from your API Management service. Keep in mind that it will also affect the test console.

If you still consider it a problem, please open a GitHub issue in the developer portal repository: https://aka.ms/apimdevportal and precisely describe your concern.


问:
Modal is hidden from other divs
I'm having a small problem with the modal; part of it is hidden by the right div.

I have two splits, one on the left where the table is shown and the other on the right where a form is shown.

On the left split there is also a button, "Open modal", which allows me to open the modal.

The problem is that once the modal is open, it is visible on the left side, while the part of the modal that ends up on the right split is hidden by the right split.

See figure for further clarification.

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.split {
            height: 100%;
            position: fixed;
            z-index: 1;
            top: 30;
            overflow-x: hidden;
            padding-top: 20px;
        }

        .left {
            left: 0;
            width: 40%;
            background-color: whitesmoke;
        }

        .right {
            right: 0;
            width: 60%;
            background-color: ghostwhite;
        }

        .centered {
            position: absolute;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .centered table {
            width: 300px;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }

        .buttons {
            display: flex;
        }

        .buttons form {
            margin: 0 10px;
        }

        .part {
            width: 200px;
            padding: 5px;
            border: 1px solid gray;
            margin: 0;
            margin-bottom: 20px;
        }

        /* The Modal (background) */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }</code>```

Parti dell'articolo

                        Numero
                        Tipo
                        Seleziona

                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo" />
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()" />

                <button id="myBtn">Open Modal</button>

                        ×

                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">

Modifica frammento

                            ID :
                            <input type="number" id="id" name="id" />

                            ID Articolo:
                            <input type="text" id="id_a" name="id_a" />

                            Numero Frammento:
                            <input type="number" id="numero" name="numero" />

                            Tipo Frammento:
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>

                            Valore Frammento:
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>

                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche"

                    </form>

```

答:
Please change position of modal from fixed to relative.</p>
```<code>.modal {
            display: none;
            /* Hidden by default */
            position: relative;
..... rest keep the same only changed position to relative
}
</code>```

Title: Modal is hidden from other divs

Body:
I'm having a small problem with the modal; part of it is hidden by the right div.

I have two splits, one on the left where the table is shown and the other on the right where a form is shown.

On the left split there is also a button, "Open modal", which allows me to open the modal.

The problem is that once the modal is open, it is visible on the left side, while the part of the modal that ends up on the right split is hidden by the right split.

See figure for further clarification.

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

.split {
            height: 100%;
            position: fixed;
            z-index: 1;
            top: 30;
            overflow-x: hidden;
            padding-top: 20px;
        }

        .left {
            left: 0;
            width: 40%;
            background-color: whitesmoke;
        }

        .right {
            right: 0;
            width: 60%;
            background-color: ghostwhite;
        }

        .centered {
            position: absolute;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .centered table {
            width: 300px;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }

        .buttons {
            display: flex;
        }

        .buttons form {
            margin: 0 10px;
        }

        .part {
            width: 200px;
            padding: 5px;
            border: 1px solid gray;
            margin: 0;
            margin-bottom: 20px;
        }

        /* The Modal (background) */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

Parti dell'articolo

                        Numero
                        Tipo
                        Seleziona

                    <form action="creaFrammento.html">
                        <input type="submit" value="Aggiungi parte articolo" />
                    </form>

                    <input type="button" value="Elimina parti articolo" onclick="confirmation()" />

                <button id="myBtn">Open Modal</button>

                        ×

                    <form method="post" id="save" action="javascript:myFunction()" class="formEdit">

Modifica frammento

                            ID :
                            <input type="number" id="id" name="id" />

                            ID Articolo:
                            <input type="text" id="id_a" name="id_a" />

                            Numero Frammento:
                            <input type="number" id="numero" name="numero" />

                            Tipo Frammento:
                            <select name="tipo" id="tipo" form="tipoform">
                                <option value="Titolo">Titolo</option>
                                <option value="Testo">Testo</option>
                                <option value="Immagine">Immagine</option>
                                <option value="Video youtube">Video youtube</option>
                            </select>

                            Valore Frammento:
                            <textarea id="valore" name="valore" rows="5" cols="30"> </textarea>

                            <button type="submit" id="save-btn" class="full">Salva modifiche</button>
                            <input type="button" id="delete-btn" value="Annulla modifiche"

                    </form>

Body:
Please change position of modal from fixed to relative.

.modal {
            display: none;
            /* Hidden by default */
            position: relative;
..... rest keep the same only changed position to relative
}


问:
Problem to connect OpenFOAM with Paraview (cannot execuete paraFoam and touch function
I got a problem of installing Paraview due to an error:

```<code>$ ParaFoam
Invalid $PV_PLUGIN_PATH and -plugin-path= not defined
No supplementary ParaView/OpenFOAM reader modules
Using builtin reader: ParaFoam -vtk

Created temporary 'cavity.foam'
/home/ofuser/OpenFOAM/OpenFOAM-v2112/bin/ParaFoam: line 423: paraview: command not found
</code>```

I am using windows version OpenFOAM-v2112-MSYS2-Terminal.

Thanks for your help!

答:
Install a regular paraview binary (windows) and use that. There isn't any reason to use the paraFoam script.
See the paraview FAQ answer on https://discourse.paraview.org and the plugin wiki</p>

Body:
I got a problem of installing Paraview due to an error:

$ ParaFoam
Invalid $PV_PLUGIN_PATH and -plugin-path= not defined
No supplementary ParaView/OpenFOAM reader modules
Using builtin reader: ParaFoam -vtk

Created temporary 'cavity.foam'
/home/ofuser/OpenFOAM/OpenFOAM-v2112/bin/ParaFoam: line 423: paraview: command not found

I am using windows version OpenFOAM-v2112-MSYS2-Terminal.

Thanks for your help!


问:
Waiting for a method in a loop in effects angular
How can I wait for the loop to finish and get the data? Thought about the forkJoin method, but without success...

    getEntities$ = createEffect(() =>
    this.actions$.pipe(
      ofType(GetEntities),
      mergeMap((s: any) =>
        // first request
        this.service.getEntities(s.id).pipe(
          map((data: Entitites[]) => {
            const entities = cloneDeep(data);
            for (const entity of entities) {
              // second request
              this.service.getAdditionalInfo(s.id, entity.id).subscribe((info: Info) => {
                entity.info = info;
              })
            }
            // getting the old data without additional info
            return entities;
          }),
          mergeMap((entities: Entities[]) => [GetEntitiesSuccess({ entities})]),
          ....
```

答:
You can achieve that using concat or forkJoin like the following:

getEntities$ = createEffect(() =>
    this.actions$.pipe(
        ofType(GetEntities),
        mergeMap((s: any) => this.service.getEntities(s.id)),
        mergeMap((data: Entitites[]) => {
            const entities = cloneDeep(data);
            return concat(
                ...entities.map((entity) =>
                    this.service.getAdditionalInfo(s.id, entity.id).pipe(map(info: Info) => {
                        entity.info = info;
                        return entity;
                    })
                )
            );
        }),
        mergeMap((entities: Entities[]) => [GetEntitiesSuccess({ entities })])
    )
);
```


问:
Java - Azure Application Insights Dynamic Tracing not working with docker images
Azure Functions has dynamic tracing functionality for Java with App Insights. Where it collects metrics against several libraries. Full list here.

As per this, for Linux, adding the config ApplicationInsightsAgent_EXTENSION_VERSION=~3 should make it work. It works as expected if the azure function is deployed as code runtime.

But it doesn't work when the azure function is deployed against docker!

答:
As of Feb 2022, dynamic tracing functionality (for Java) automatically works against code runtime.

To make it work with a docker image, this is what I did (May be just a matter of time if it starts functioning automatically against docker images as well).

To make it work in the meantime:

mvn clean package

Update your Dockerfile:

```<code>ARG JAVA_VERSION=8
# This image additionally contains function core tools – useful when using custom extensions
#FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-core-tools AS installer-env
FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-build AS installer-env

COPY . /src/java-function-app

RUN cd /src/java-function-app && \
    mkdir -p /home/site/wwwroot && \
    cd ./target/azure-functions/ && \
    cd $(ls -d */|head -n 1) && \
    cp -a . /home/site/wwwroot && \
    cd /home/site/wwwroot && \
    curl -SL --output applicationinsights-agent-3.2.6.jar https://github.com/microsoft/ApplicationInsights-Java/releases/download/3.2.6/applicationinsights-agent-3.2.6.jar

# This image is ssh enabled
FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-appservice
# This image isn't ssh enabled
#FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION

ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true

COPY --from=installer-env ["/home/site/wwwroot", "/home/site/wwwroot"]
</code>```

The above assumes that the mvn clean package has been done before the docker image is created.

Finally, add the path to the agent as JAVA_OPTS. This is how my pom.xml looks:

            <plugin>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-functions-maven-plugin</artifactId>
                <version>${azure.functions.maven.plugin.version}</version>
                <configuration>
                    <appName>${functionAppName}</appName>
                    <resourceGroup>xxxxx</resourceGroup>
                    <appServicePlanName>dockertemp2-appservice</appServicePlanName>
                     <region>centralus</region>
                     <pricingTier>P1V2</pricingTier>
                    <runtime>
                        <os>docker</os>
                       <image>xxxxx.azurecr.io/dockertemp:v0.0.2</image>
                        <serverId>SERVER_ID</serverId>
                        <registryUrl>xxxxx.azurecr.io</registryUrl>
                    </runtime>
                    <appSettings>
                        <property>
                            <name>FUNCTIONS_EXTENSION_VERSION</name>
                            <value>~3</value>
                        </property>
                        <property>
                            <name>JAVA_OPTS</name>
                            <value>-javaagent:/home/site/wwwroot/applicationinsights-agent-3.2.6.jar</value>
                        </property>
                    </appSettings>
                </configuration>
                <executions>
                    <execution>
                        <id>package-functions</id>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
```
<p>Finally, push the docker image and deploy the azure function.</p>
```mvn clean install package -DskipTests
docker build --tag xxxxx.azurecr.io/dockertemp:v0.0.2 .
docker push xxxxx.azurecr.io/dockertemp:v0.0.2
mvn azure-functions:deploy
```

Finally, able to see dynamic tracing in action:

Body:
As of Feb 2022, dynamic tracing functionality (for Java) automatically works against code runtime.

To make it work with a docker image, this is what I did (May be just a matter of time if it starts functioning automatically against docker images as well).

To make it work in the meantime:

mvn clean package

Update your Dockerfile:

ARG JAVA_VERSION=8
# This image additionally contains function core tools – useful when using custom extensions
#FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-core-tools AS installer-env
FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-build AS installer-env

COPY . /src/java-function-app

RUN cd /src/java-function-app && \
    mkdir -p /home/site/wwwroot && \
    cd ./target/azure-functions/ && \
    cd $(ls -d */|head -n 1) && \
    cp -a . /home/site/wwwroot && \
    cd /home/site/wwwroot && \
    curl -SL --output applicationinsights-agent-3.2.6.jar https://github.com/microsoft/ApplicationInsights-Java/releases/download/3.2.6/applicationinsights-agent-3.2.6.jar

# This image is ssh enabled
FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION-appservice
# This image isn't ssh enabled
#FROM mcr.microsoft.com/azure-functions/java:3.0-java$JAVA_VERSION

ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true

COPY --from=installer-env ["/home/site/wwwroot", "/home/site/wwwroot"]

The above assumes that the mvn clean package has been done before the docker image is created.

Finally, add the path to the agent as JAVA_OPTS. This is how my pom.xml looks:

            <plugin>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-functions-maven-plugin</artifactId>
                <version>${azure.functions.maven.plugin.version}</version>
                <configuration>
                    <appName>${functionAppName}</appName>
                    <resourceGroup>xxxxx</resourceGroup>
                    <appServicePlanName>dockertemp2-appservice</appServicePlanName>
                     <region>centralus</region>
                     <pricingTier>P1V2</pricingTier>
                    <runtime>
                        <os>docker</os>
                       <image>xxxxx.azurecr.io/dockertemp:v0.0.2</image>
                        <serverId>SERVER_ID</serverId>
                        <registryUrl>xxxxx.azurecr.io</registryUrl>
                    </runtime>
                    <appSettings>
                        <property>
                            <name>FUNCTIONS_EXTENSION_VERSION</name>
                            <value>~3</value>
                        </property>
                        <property>
                            <name>JAVA_OPTS</name>
                            <value>-javaagent:/home/site/wwwroot/applicationinsights-agent-3.2.6.jar</value>
                        </property>
                    </appSettings>
                </configuration>
                <executions>
                    <execution>
                        <id>package-functions</id>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Finally, push the docker image and deploy the azure function.

mvn clean install package -DskipTests
docker build --tag xxxxx.azurecr.io/dockertemp:v0.0.2 .
docker push xxxxx.azurecr.io/dockertemp:v0.0.2
mvn azure-functions:deploy

Finally, able to see dynamic tracing in action:


问:
htaccess Clean URL Gives Too Many Redirects
I have the code below in my .htaccess file to remove php from the filename in the URL

```<code># Apache Rewrite Rules
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

I now need to change the URL

```<code>editpermit.php?type=edit&id=1
</code>```

to

```<code>editpermit/edit/1
</code>```

I've added below but I get the error 'Request exceeded the limit of 10 internal redirects due to probable configuration error.'. Other posts say to add an L to the end to show it's the last line but it's not making any difference.

```<code>RewriteRule ^editpermit/([a-z]*)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]
</code>```

I plan to have a few pages that will use this configuration so I need to know how to add these too at a later time

My full htaccess file is below

```<code># Error pages
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 405 /405.php
ErrorDocument 500 /500.php
ErrorDocument 503 /503.php

# Apache Rewrite Rules
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*)$ $1.php
RewriteRule ^editpermit/([a-z]*)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]
</code>```

答:
```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

The problem is with your first "generic" rule that appends the .php extension. When you request editpermit/edit/1 and editpermit.php exists then the second condition is successful (REQUEST_FILENAME contains editpermit, not editpermit/edit/1), but it rewrites to editpermit/edit/1.php based on the requested URL-path captured from the RewriteRule pattern. This then causes a rewrite loop since editpermit/edit/1.php also matches this rule, rewriting the request a second time to /editpermit/edit/1.php.php etc. etc.

You need to write the above rule like this instead:

```<code>RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]
</code>```

Now you are checking the same file that you are ultimately rewriting to.

See also my answer to the following question on ServerFault which goes into more detail:

https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error

(You don't need the first condition that checks the request does not map to a directory to then check that the request does map to a file.)

This can also be resolved by reversing the order of your rules (which you should do anyway). For example:

```<code>RewriteEngine On

RewriteRule ^editpermit/([a-z]+)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]
</code>```

NB: I changed the quantifier that matches the 2nd path segment in the first rule from * to +. Presumably this cannot be omitted? (Although if it was it wouldn't have matched anyway.)

Body:
I have the code below in my .htaccess file to remove php from the filename in the URL

# Apache Rewrite Rules
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

I now need to change the URL

editpermit.php?type=edit&id=1

to

editpermit/edit/1

I've added below but I get the error 'Request exceeded the limit of 10 internal redirects due to probable configuration error.'. Other posts say to add an L to the end to show it's the last line but it's not making any difference.

RewriteRule ^editpermit/([a-z]*)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]

I plan to have a few pages that will use this configuration so I need to know how to add these too at a later time

My full htaccess file is below

# Error pages
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 405 /405.php
ErrorDocument 500 /500.php
ErrorDocument 503 /503.php

# Apache Rewrite Rules
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*)$ $1.php
RewriteRule ^editpermit/([a-z]*)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]

Body:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

The problem is with your first "generic" rule that appends the .php extension. When you request editpermit/edit/1 and editpermit.php exists then the second condition is successful (REQUEST_FILENAME contains editpermit, not editpermit/edit/1), but it rewrites to editpermit/edit/1.php based on the requested URL-path captured from the RewriteRule pattern. This then causes a rewrite loop since editpermit/edit/1.php also matches this rule, rewriting the request a second time to /editpermit/edit/1.php.php etc. etc.

You need to write the above rule like this instead:

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

Now you are checking the same file that you are ultimately rewriting to.

See also my answer to the following question on ServerFault which goes into more detail:

https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error

(You don't need the first condition that checks the request does not map to a directory to then check that the request does map to a file.)

This can also be resolved by reversing the order of your rules (which you should do anyway). For example:

RewriteEngine On

RewriteRule ^editpermit/([a-z]+)/([0-9]+)$ editpermit.php?type=$1&id=$2 [NC,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

NB: I changed the quantifier that matches the 2nd path segment in the first rule from * to +. Presumably this cannot be omitted? (Although if it was it wouldn't have matched anyway.)


问:
Installing npm on WSL2 Ubuntu
I have a Laravel application that needs sass/scss.

I'm trying to install NPM using npm install but it keeps telling me

npm ERR! code EBADPLATFORM

npm ERR! notsup Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin"} (current: {"os":"linux","arch":"x64"})

npm ERR! notsup Valid OS:    darwin

npm ERR! notsup Valid Arch:  undefined

npm ERR! notsup Actual OS:   linux

npm ERR! notsup Actual Arch: x64

I'm using the latest Ubuntu 20.04 on WSL2. I've tried several attempts to solve this by:

Reinstalling Node and NPM

Changing the owner of the folder (laravel folder) to me

Any advice?

答:
I'm guessing it has to do with using WSL 2, since in Ubuntu it shouldn't cause any trouble.

You could try npm i fsevents --force. That way it will disable the recommended protections and install it anyway.

Title: Installing npm on WSL2 Ubuntu


问:
Increase and reduce index withing a fixed circular range in JS
I have a circular range of ascii values of a-z, from 97 to 122.

I am having trouble with decreasing the value, suppose the current value is 100 and i want to reduce it by 4 and it should return 122.

```<code>const startIndex=97
const endIndex=122

let increaseBy=reduceBy=5
let currentIndex=122
// increment
// this works
currentIndex=startIndex+((currentIndex-startIndex+increaseBy)%26)

// decrement
// need help
currentIndex=attempted_something_that_you_will_find_it_as_dumb
</code>```

答:
The solution @thst gave works well. In short I'll mention my usage of the code

```<code>const startIndex = 97;
const endIndex = 122;
let currentIndex = 122;
//this value is varies according to the input i take
let increaseBy = (reduceBy = 5);

// increment
currentIndex = startIndex + ((currentIndex - startIndex + increaseBy) % 26);
// decrement
const milansConst=7;
currentIndex = startIndex + ((currentIndex - reduceBy + milansConst) % 26);
</code>```

milansConst is a mysterious number (there is no logic to it) my friend came up with to get the decrement expression he made work.

Body:
I have a circular range of ascii values of a-z, from 97 to 122.

I am having trouble with decreasing the value, suppose the current value is 100 and i want to reduce it by 4 and it should return 122.

const startIndex=97
const endIndex=122

let increaseBy=reduceBy=5
let currentIndex=122
// increment
// this works
currentIndex=startIndex+((currentIndex-startIndex+increaseBy)%26)

// decrement
// need help
currentIndex=attempted_something_that_you_will_find_it_as_dumb

Body:
The solution @thst gave works well. In short I'll mention my usage of the code

const startIndex = 97;
const endIndex = 122;
let currentIndex = 122;
//this value is varies according to the input i take
let increaseBy = (reduceBy = 5);

// increment
currentIndex = startIndex + ((currentIndex - startIndex + increaseBy) % 26);
// decrement
const milansConst=7;
currentIndex = startIndex + ((currentIndex - reduceBy + milansConst) % 26);

milansConst is a mysterious number (there is no logic to it) my friend came up with to get the decrement expression he made work.


问:
changing key trust level (validity) with gpgme
GPGME provides information about a key's trust level as the owner_trust field which is of gpgme_validity_t type. However, I could not find a function in the documentation or the gpgme.h header file that allows me to change the validity of a key.

The GnuPG command line tool sure allows to change the trust level of a key:

$ gpg --edit-key alice@example.com
> trust
```

Does the GPGME library even support changing the owner_trust field? If so, how do I use it?

I am using the newest version of GPGME which is 1.16.0 (commit hash 1021c8645555502d914afffaa3707609809c9459).

答:
It should be possible to use gpgme_op_interact to accomplish this.

The following demonstrates the process with Python bindings, but analogous code should be possible to write with the C API.

import gpg

def trust_at(level):
    done = False
    def interact_cb(status, arg):
        nonlocal done
        if status in ('KEY_CONSIDERED', 'GOT_IT', ''):
            return
        if status == 'GET_LINE':
            if arg == 'keyedit.prompt':
                if done:
                    return 'quit'
                done = True
                return 'trust'
            if arg == 'edit_ownertrust.value':
                return level
        # needed if we set trust level to 5
        if (status, arg) == ('GET_BOOL', 'edit_ownertrust.set_ultimate.okay'):
            return 'y'
        assert False
    return interact_cb

with gpg.Context() as gnupg:
    key = gnupg.get_key(FINGERPRINT)
    gnupg.interact(key, trust_at('4'))
```

Body:
GPGME provides information about a key's trust level as the owner_trust field which is of gpgme_validity_t type. However, I could not find a function in the documentation or the gpgme.h header file that allows me to change the validity of a key.

The GnuPG command line tool sure allows to change the trust level of a key:

$ gpg --edit-key alice@example.com
> trust

Does the GPGME library even support changing the owner_trust field? If so, how do I use it?

I am using the newest version of GPGME which is 1.16.0 (commit hash 1021c8645555502d914afffaa3707609809c9459).


问:
Optaplanner - ConstructionHeuristics find a feasible solution before all planning entity get initialized
I have this setting:

%test.quarkus.optaplanner.solver.termination.best-score-limit=0hard/*soft

In ConstructionHeuristics phase, if optaplanner get a 0 HARD score (feasible solution) before assigning all planning entities an initial value, then it becomes infeasible again (-1 HARD) after assigning more planning entities initial value, I noticed when the construction heuristics phase ends, optaplanner will not do LOCAL SEARCH and just report the infeasible solution as final best solution.

Shouldn't the final best solution be the one after all planning entities got assigned a value and starts from there to check whether to terminate the search?

I even have hard constraints to not allow any Planning entities to have null planning variable. but before the planning entity got initialized in Construction Heuristics phase, the hard constraint does not seem to kick in.

Is there a way to add a constraint for uninitialized planning entity?
How to let optaplanner to take the final best solution only after all planning entities are initialized?

Here are the logs I see in my case:

```<code>2022-02-09 14:20:05,126 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving started: time spent (90), best score (-30init/0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
2022-02-09 14:20:05,198 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (0), time spent (170), score (-28init/-2hard/-5soft), selected move count (32), picked move ([a.0 {null -> MANUAL_ASSEMBLY}, a.0 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,247 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (1), time spent (219), score (-26init/-1hard/-5soft), selected move count (33), picked move ([f.4 {null -> MANUAL_ASSEMBLY}, f.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,286 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (2), time spent (258), score (-24init/-1hard/-5soft), selected move count (34), picked move ([2.f {null -> MANUAL_ASSEMBLY}, 2.f {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,315 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (3), time spent (287), score (-22init/-1hard/-4soft), selected move count (35), picked move ([9.8 {null -> MANUAL_ASSEMBLY}, 9.8 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,338 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (4), time spent (310), score (-20init/-1hard/-4soft), selected move count (36), picked move ([6.c {null -> MANUAL_ASSEMBLY}, 6.c {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,362 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (5), time spent (334), score (-18init/-1hard/-4soft), selected move count (37), picked move ([8.3 {null -> MANUAL_ASSEMBLY}, 8.3 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,384 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (6), time spent (356), score (-16init/-1hard/-4soft), selected move count (38), picked move ([f.2 {null -> MANUAL_ASSEMBLY}, f.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,400 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (7), time spent (372), score (-14init/-1hard/-3soft), selected move count (39), picked move ([4.6 {null -> MANUAL_ASSEMBLY}, 4.6 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,415 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (8), time spent (387), score (-12init/-1hard/-3soft), selected move count (40), picked move ([8.2 {null -> MANUAL_ASSEMBLY}, 8.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,428 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (9), time spent (400), score (-10init/0hard/-3soft), selected move count (41), picked move ([a.4 {null -> MANUAL_ASSEMBLY}, a.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,440 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (10), time spent (412), score (-8init/0hard/-2soft), selected move count (42), picked move ([4.5 {null -> MANUAL_ASSEMBLY}, 4.5 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,453 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (11), time spent (425), score (-6init/0hard/-2soft), selected move count (43), picked move ([5.d {null -> MANUAL_ASSEMBLY}, 5.d {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,474 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (12), time spent (446), score (-4init/0hard/-2soft), selected move count (44), picked move ([8.a {null -> MANUAL_ASSEMBLY}, 8.a {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,501 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (13), time spent (473), score (-2init/0hard/-2soft), selected move count (45), picked move ([6.3 {null -> MANUAL_ASSEMBLY}, 6.3 {null -> a.0}]).
2022-02-09 14:20:05,530 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (14), time spent (502), score (-1hard/-2soft), selected move count (46), picked move ([3.b {null -> MANUAL_ASSEMBLY}, 3.b {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,532 INFO  [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1) Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft), score calculation speed (1446/sec), step total (15).
2022-02-09 14:20:05,641 DEBUG [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1)     LS step (0), time spent (613), score (0hard/-2soft), new best score (0hard/-2soft), accepted/selected move count (100/100), picked move ([a.0..6.3] {f.4} <-reversing-> [8.2..f.2] {a.4}).
2022-02-09 14:20:05,642 INFO  [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1) Local Search phase (1) ended: time spent (614), best score (0hard/-2soft), score calculation speed (1010/sec), step total (1).
2022-02-09 14:20:05,644 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving ended: time spent (614), best score (0hard/-2soft), score calculation speed (1120/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
Explanation of score (-1hard/-2soft):
</code>```

From the log, it says "Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft)" but why LOCAL SEARCH remembers the best score as "new best score (0hard/-2soft)" and then stopped, but reporting finalbestsolution with "Explanation of score (-1hard/-2soft)"?

答:
I figured out what went wrong.

Radovan is correct that optaplanner will use the score after all planning variable is initialized.

But my problem is I see the solution score in the planning solution is different from the score I get by using scoreManager. Causing the confusion.

What caused this is that I used to have the planning entity, and my constraints (written in constraints stream) all use the planning entity as initial match statement (".from(...)"), but later on in my domain model, I decided to change the planning entity to another class, and keep the class as the anchor of the new planning entity. And I still kept all the old constraints which match using the old class which is no longer the planning entity, because I thought its the anchor so I can trace to all the other planning entities. Basically I thought I could get away from not having to rewrite the constraints after changing the planning entity to another class.

That caused many unexplainable problem, one of it is the score in the solution is different from that reported by scoreManager.

I found this problem through this link:

OptaPlanner Solution's score not matches the score given by `ScoreManager::explainScore`

After I set FULL_ASSERT on, I immediately see optaplanner report error on the constraints. So I took the time to rewrite the constraints and now the problem is gone.

Body:
I have this setting:

%test.quarkus.optaplanner.solver.termination.best-score-limit=0hard/*soft

In ConstructionHeuristics phase, if optaplanner get a 0 HARD score (feasible solution) before assigning all planning entities an initial value, then it becomes infeasible again (-1 HARD) after assigning more planning entities initial value, I noticed when the construction heuristics phase ends, optaplanner will not do LOCAL SEARCH and just report the infeasible solution as final best solution.

Shouldn't the final best solution be the one after all planning entities got assigned a value and starts from there to check whether to terminate the search?

I even have hard constraints to not allow any Planning entities to have null planning variable. but before the planning entity got initialized in Construction Heuristics phase, the hard constraint does not seem to kick in.

Is there a way to add a constraint for uninitialized planning entity?
How to let optaplanner to take the final best solution only after all planning entities are initialized?

Here are the logs I see in my case:

2022-02-09 14:20:05,126 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving started: time spent (90), best score (-30init/0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
2022-02-09 14:20:05,198 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (0), time spent (170), score (-28init/-2hard/-5soft), selected move count (32), picked move ([a.0 {null -> MANUAL_ASSEMBLY}, a.0 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,247 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (1), time spent (219), score (-26init/-1hard/-5soft), selected move count (33), picked move ([f.4 {null -> MANUAL_ASSEMBLY}, f.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,286 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (2), time spent (258), score (-24init/-1hard/-5soft), selected move count (34), picked move ([2.f {null -> MANUAL_ASSEMBLY}, 2.f {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,315 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (3), time spent (287), score (-22init/-1hard/-4soft), selected move count (35), picked move ([9.8 {null -> MANUAL_ASSEMBLY}, 9.8 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,338 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (4), time spent (310), score (-20init/-1hard/-4soft), selected move count (36), picked move ([6.c {null -> MANUAL_ASSEMBLY}, 6.c {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,362 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (5), time spent (334), score (-18init/-1hard/-4soft), selected move count (37), picked move ([8.3 {null -> MANUAL_ASSEMBLY}, 8.3 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,384 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (6), time spent (356), score (-16init/-1hard/-4soft), selected move count (38), picked move ([f.2 {null -> MANUAL_ASSEMBLY}, f.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,400 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (7), time spent (372), score (-14init/-1hard/-3soft), selected move count (39), picked move ([4.6 {null -> MANUAL_ASSEMBLY}, 4.6 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,415 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (8), time spent (387), score (-12init/-1hard/-3soft), selected move count (40), picked move ([8.2 {null -> MANUAL_ASSEMBLY}, 8.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,428 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (9), time spent (400), score (-10init/0hard/-3soft), selected move count (41), picked move ([a.4 {null -> MANUAL_ASSEMBLY}, a.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,440 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (10), time spent (412), score (-8init/0hard/-2soft), selected move count (42), picked move ([4.5 {null -> MANUAL_ASSEMBLY}, 4.5 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,453 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (11), time spent (425), score (-6init/0hard/-2soft), selected move count (43), picked move ([5.d {null -> MANUAL_ASSEMBLY}, 5.d {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,474 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (12), time spent (446), score (-4init/0hard/-2soft), selected move count (44), picked move ([8.a {null -> MANUAL_ASSEMBLY}, 8.a {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,501 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (13), time spent (473), score (-2init/0hard/-2soft), selected move count (45), picked move ([6.3 {null -> MANUAL_ASSEMBLY}, 6.3 {null -> a.0}]).
2022-02-09 14:20:05,530 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (14), time spent (502), score (-1hard/-2soft), selected move count (46), picked move ([3.b {null -> MANUAL_ASSEMBLY}, 3.b {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,532 INFO  [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1) Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft), score calculation speed (1446/sec), step total (15).
2022-02-09 14:20:05,641 DEBUG [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1)     LS step (0), time spent (613), score (0hard/-2soft), new best score (0hard/-2soft), accepted/selected move count (100/100), picked move ([a.0..6.3] {f.4} <-reversing-> [8.2..f.2] {a.4}).
2022-02-09 14:20:05,642 INFO  [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1) Local Search phase (1) ended: time spent (614), best score (0hard/-2soft), score calculation speed (1010/sec), step total (1).
2022-02-09 14:20:05,644 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving ended: time spent (614), best score (0hard/-2soft), score calculation speed (1120/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
Explanation of score (-1hard/-2soft):

From the log, it says "Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft)" but why LOCAL SEARCH remembers the best score as "new best score (0hard/-2soft)" and then stopped, but reporting finalbestsolution with "Explanation of score (-1hard/-2soft)"?


问:
getopt invalid option command line C
Upon running salary -b -r 4 -t 10 75000 on the command line I am receiving the following errors and am unsure of why. What exactly is the reason I am getting invalid option and what is the solution?

salary: invalid option -- 'r'

salary: invalid option -- 't'

salary: Missing taxes.

usage: salary [-bv] [r rnum] -t tnum base

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int debug = 0;

int main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;
    int c, err = 0;
    int tflag=0;
    double baseSalary,bonus1,bonus2,percentRaise,taxes,finalSalary = 0;

    static char usage[] = "usage: %s [-bv] [r rnum] -t tnum base\n";

    while ((c = getopt(argc, argv, "bc:d:")) != -1)
        switch (c) {
        case 'd':
            debug = 1;
            break;
        case 'b':
            bonus1=5000;
            break;
        case 'v':
            bonus2=6000;
            break;
        case 'r':
            percentRaise = atoi(optarg);
            if ((percentRaise<2) || (percentRaise>10)){
                fprintf(stderr, "%s:Out of bound raise percent.\n", argv[0]);
                exit(1);
            }
            percentRaise/=10;
            percentRaise+=1;
            break;
        case 't':
            taxes = atoi(optarg);
            if ((taxes<5)||(taxes)>30){
                fprintf(stderr, "%s:Out of bound tax percent.\n", argv[0]);
                exit(1);
            }
            taxes /=10;
            taxes = 1-taxes;
            tflag = 1;
            break;
        case '?':
            err = 1;
            break;
        }
    if (tflag == 0) {   /* -c was mandatory */
        fprintf("Result: Missing taxes.\n");
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    if (optind < argc){ /* these are the arguments after the command-line options */
        baseSalary = atoi(argv[optind]);
        if ((baseSalary>90000) || (baseSalary<20000)){
            fprintf(stderr, "%s:Out of bound salary\n", argv[0]);
            fprintf(stderr, usage, argv[0]);
            exit(1);
        }
    }
    finalSalary += baseSalary;
    finalSalary+=bonus2;
    finalSalary*=percentRaise;
    finalSalary+=bonus1;
    finalSalary*=taxes;

    printf("Result: %.2f\n", finalSalary);
    exit(0);
}
</code>```

答:
Your option string doesn't match the options you're expecting.

A letter in the option string followed by a : specifies an option that takes a parameter, while a letter that is not followed by a : is for an option that does not take an argument.

That means your option string "bc:d:" is expecting a b option with no argument, a c option with an argument, and a d option with an argument.  That does not correspond to your usage.  You instead want:

```<code>"bdvr:t:"
</code>```

Title: getopt invalid option command line C

Body:
Upon running salary -b -r 4 -t 10 75000 on the command line I am receiving the following errors and am unsure of why. What exactly is the reason I am getting invalid option and what is the solution?

salary: invalid option -- 'r'

salary: invalid option -- 't'

salary: Missing taxes.

usage: salary [-bv] [r rnum] -t tnum base

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int debug = 0;

int main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;
    int c, err = 0;
    int tflag=0;
    double baseSalary,bonus1,bonus2,percentRaise,taxes,finalSalary = 0;

    static char usage[] = "usage: %s [-bv] [r rnum] -t tnum base\n";

    while ((c = getopt(argc, argv, "bc:d:")) != -1)
        switch (c) {
        case 'd':
            debug = 1;
            break;
        case 'b':
            bonus1=5000;
            break;
        case 'v':
            bonus2=6000;
            break;
        case 'r':
            percentRaise = atoi(optarg);
            if ((percentRaise<2) || (percentRaise>10)){
                fprintf(stderr, "%s:Out of bound raise percent.\n", argv[0]);
                exit(1);
            }
            percentRaise/=10;
            percentRaise+=1;
            break;
        case 't':
            taxes = atoi(optarg);
            if ((taxes<5)||(taxes)>30){
                fprintf(stderr, "%s:Out of bound tax percent.\n", argv[0]);
                exit(1);
            }
            taxes /=10;
            taxes = 1-taxes;
            tflag = 1;
            break;
        case '?':
            err = 1;
            break;
        }
    if (tflag == 0) {   /* -c was mandatory */
        fprintf("Result: Missing taxes.\n");
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    if (optind < argc){ /* these are the arguments after the command-line options */
        baseSalary = atoi(argv[optind]);
        if ((baseSalary>90000) || (baseSalary<20000)){
            fprintf(stderr, "%s:Out of bound salary\n", argv[0]);
            fprintf(stderr, usage, argv[0]);
            exit(1);
        }
    }
    finalSalary += baseSalary;
    finalSalary+=bonus2;
    finalSalary*=percentRaise;
    finalSalary+=bonus1;
    finalSalary*=taxes;

    printf("Result: %.2f\n", finalSalary);
    exit(0);
}

Body:
Your option string doesn't match the options you're expecting.

A letter in the option string followed by a : specifies an option that takes a parameter, while a letter that is not followed by a : is for an option that does not take an argument.

That means your option string "bc:d:" is expecting a b option with no argument, a c option with an argument, and a d option with an argument.  That does not correspond to your usage.  You instead want:

"bdvr:t:"