问:
Removing a word from a variable in Applescript
I'm pretty newbie at Applescript and I can't work out how to remove a word from a variable if the word contains a “#” in it.

My script gets this error -> "Can’t make word into type integer." number -1700 from word to integer

Here's my script so far:

```<code>activate application "Grids"
delay 2
tell application "System Events"
    keystroke "a" using command down
    delay 0.25
    keystroke "c" using command down
    delay 0.25
    set Description to the clipboard
    if any word in Description contains "#" then delete that word
    return Description
end tell
</code>```

Any pointers?

Cheers,
Chris

答:
To get text out of the clipboard, use (clipboard as text). The clipboard can contain almost anything, even multiple objects, in multiple formats, so as text gives you a string to work with.

And watch out: 'Description' appears to be part of some existing appleScript 'terminology', at least on the Mac I have right here, so I am changing your identifier to desc here:

```<code>activate application "Grids"
delay 2
tell application "System Events"
    keystroke "a" using command down
    delay 0.25
    keystroke "c" using command down
    delay 0.25
    set desc to the clipboard as text
end tell

set out to {}
set tids to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "

repeat with anItem in (text items of desc)
    set str to (anItem as string)
    if (str does not contain "#") then
        set end of out to str
    end if
end repeat

set outStr to out as string
set AppleScript's text item delimiters to tids
return outStr
</code>```

This code just returns the text you are looking for. It does not re-insert the groomed string, or do anything else interesting.

I assume you're going to tell System Events to paste it via cmd-v. (Remember to set the clipboard to outStr before you paste!)

AppleScript's text item delimiters allows the string to be split and reassembled using a space (or any other token you wish). For code hygiene reasons, it's wise practice to store it before changing it, then reset it to its original value afterwards, as shown here, otherwise odd things might happen in scripts which expect it to have the default value.

Body:
I'm pretty newbie at Applescript and I can't work out how to remove a word from a variable if the word contains a “#” in it.

My script gets this error -> "Can’t make word into type integer." number -1700 from word to integer

Here's my script so far:

activate application "Grids"
delay 2
tell application "System Events"
    keystroke "a" using command down
    delay 0.25
    keystroke "c" using command down
    delay 0.25
    set Description to the clipboard
    if any word in Description contains "#" then delete that word
    return Description
end tell

Any pointers?

Cheers,
Chris

Body:
To get text out of the clipboard, use (clipboard as text). The clipboard can contain almost anything, even multiple objects, in multiple formats, so as text gives you a string to work with.

And watch out: 'Description' appears to be part of some existing appleScript 'terminology', at least on the Mac I have right here, so I am changing your identifier to desc here:

activate application "Grids"
delay 2
tell application "System Events"
    keystroke "a" using command down
    delay 0.25
    keystroke "c" using command down
    delay 0.25
    set desc to the clipboard as text
end tell

set out to {}
set tids to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "

repeat with anItem in (text items of desc)
    set str to (anItem as string)
    if (str does not contain "#") then
        set end of out to str
    end if
end repeat

set outStr to out as string
set AppleScript's text item delimiters to tids
return outStr

This code just returns the text you are looking for. It does not re-insert the groomed string, or do anything else interesting.

I assume you're going to tell System Events to paste it via cmd-v. (Remember to set the clipboard to outStr before you paste!)

AppleScript's text item delimiters allows the string to be split and reassembled using a space (or any other token you wish). For code hygiene reasons, it's wise practice to store it before changing it, then reset it to its original value afterwards, as shown here, otherwise odd things might happen in scripts which expect it to have the default value.


来源: stackexchange

问:
Adding custom validator to whole form group in Angular Reactive From
I'm dynamically creating reactive forms in Angular based on JSON data received from API. Sometimes form has only several formControls but sometimes there are a lot of form groups or formArrays with FormGroups.

I have a question about FormArray with several FormGroups. In this FormGroups some FormControls can be required and some not. But the whole FormGroup is not required. Only if some FormControls in group are edited, after that whole form group must be valid (every required FormControl can't be empty).

So my question is how to create custom validator for whole FormGroup, which will secure that if every FormControl in these concrete group will be empty, then this group will be valid. But if for example one FormControl will be edited, then every required FormControl must be filled.

Thanks a lot for your ideas.

答:
What about trying this simple solution

this is my form init

```<code>this.sponsorshipForm = this.fb.group(
  {
    startDate: ['', [Validators.required]],
    endDate: ['', [Validators.required]]
  },
  { validators: [this.sponsorshipDurationValidation] }
);
</code>```

and this is my validator you can make whatever you need and customize it

```<code>sponsorshipDurationValidation(form: FormGroup) {
   if (form.value.startDate && form.value.end) {
     console.log('form ', form, form.status);
   }
   if (something false happen or not valid value) {
     return { validUrl: true };
  }
  return null;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What about trying this simple solution

this is my form init

this.sponsorshipForm = this.fb.group(
  {
    startDate: ['', [Validators.required]],
    endDate: ['', [Validators.required]]
  },
  { validators: [this.sponsorshipDurationValidation] }
);

and this is my validator you can make whatever you need and customize it

sponsorshipDurationValidation(form: FormGroup) {
   if (form.value.startDate && form.value.end) {
     console.log('form ', form, form.status);
   }
   if (something false happen or not valid value) {
     return { validUrl: true };
  }
  return null;
}


问:
Need to retain a CFSocketRef?
I am facing a problem: I have two view controllers, viewController1, and viewController2.
Here is the method I'm concerned about in viewController1:

```<code>-(void)msgToServer:(NSString*)identifier:(NSString *)_username{
    NSString *message = [NSString stringWithFormat:@"%@|%@|<END>", identifier, _username];
    CFDataRef messageData = (CFDataRef)[message dataUsingEncoding:NSUTF8StringEncoding];

    CFSocketSendData(s, NULL, messageData, 0);
}
</code>```

this method is working perfectly in viewController1.

Now I am calling this method from viewController2. I am passing two arguments, identifier and _username. It generates the string perfectly, but when it reaches the last line it misses the value of s -- which is a CFSocketRef.
What should I do so that s will retain its value, even if I am in viewController2?

Code from viewController2 which calls the above method:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    WatchListViewController *watchListViewController = [[WatchListViewController alloc]init];
    [watchListViewController msgToServer:@"PREQ" :userName];
}
</code>```

Thanks in advance.

答:
Thanx to all who helped me well i solved this problem in this way:
when I push from viewController1 to viewController2 i am passing two parameters "username" and "s" to viewController2 and then I write this method in viewController2.

```<code>-(void)msgToServer:(NSString*)identifier:(NSString *)_username{
    NSString *message = [NSString stringWithFormat:@"%@|%@|<END>", identifier, _username];
    CFDataRef messageData = (CFDataRef)[message dataUsingEncoding:NSUTF8StringEncoding];

    CFSocketSendData(s, NULL, messageData, 0);
}
</code>```

then I am calling this method in the same view controller and it works perfectly. I think this is the only solution which i find. if any body can make it more efficient then you are welcome. :)

ContentLicense: CC BY-SA 3.0

Title: Need to retain a CFSocketRef?

Body:
I am facing a problem: I have two view controllers, viewController1, and viewController2.
Here is the method I'm concerned about in viewController1:

-(void)msgToServer:(NSString*)identifier:(NSString *)_username{
    NSString *message = [NSString stringWithFormat:@"%@|%@|<END>", identifier, _username];
    CFDataRef messageData = (CFDataRef)[message dataUsingEncoding:NSUTF8StringEncoding];

    CFSocketSendData(s, NULL, messageData, 0);
}

this method is working perfectly in viewController1.

Now I am calling this method from viewController2. I am passing two arguments, identifier and _username. It generates the string perfectly, but when it reaches the last line it misses the value of s -- which is a CFSocketRef.
What should I do so that s will retain its value, even if I am in viewController2?

Code from viewController2 which calls the above method:

- (void)viewDidLoad {
    [super viewDidLoad];
    WatchListViewController *watchListViewController = [[WatchListViewController alloc]init];
    [watchListViewController msgToServer:@"PREQ" :userName];
}

Thanks in advance.

Body:
Thanx to all who helped me well i solved this problem in this way:
when I push from viewController1 to viewController2 i am passing two parameters "username" and "s" to viewController2 and then I write this method in viewController2.

-(void)msgToServer:(NSString*)identifier:(NSString *)_username{
    NSString *message = [NSString stringWithFormat:@"%@|%@|<END>", identifier, _username];
    CFDataRef messageData = (CFDataRef)[message dataUsingEncoding:NSUTF8StringEncoding];

    CFSocketSendData(s, NULL, messageData, 0);
}

then I am calling this method in the same view controller and it works perfectly. I think this is the only solution which i find. if any body can make it more efficient then you are welcome. :)


问:
Find Array around Maximum Values of an Array
i have a quite complicated question here which i am working on. It's extremely difficult to describe in words, so i will try to explain it with an example.

Assume i have a matrix of values:

```<code>A =

[31 85 36 71 51]
[12 33 74 39 12]
[67 11 13 14 18]
[35 36 84 33 57]
</code>```

Now, i want to first find a maximum vector in the first dimension, which is easy:

```<code>[max_vector,~] = max(A,[],1);

max_vector=[67,85, 84, 71,57]
</code>```

Now i want to get a "slimmed" matrix with values around the maxima (periodical indices):

```<code>Desired_Matrix =

 [12 36 36 33 18]
 [67 85 84 71 57]
 [35 33 13 39 51]
</code>```

This is the matrix with the vectors around the maximum values of matrix A. Can someone tell me how to do this without using a double for loop?

Thank you!

答:
just for your information, here is the generalized form for the 3D-Case:</p>

```<code>A = zeros(3,5,5);

for id = 1: 20
    A(:,:,id) = id;

    if id == 10
        A(:,:,id) = 100;
    end

end

% Relative rows of neighbours, i.e. this is [-1, 0, 1] for +/- one row
p = -1:1;
% Get A row and column counts for ease
[nr, nc, nz] = size(A);
% Get max indices
[~,idx] = max( A, [], 3 );
% Handle overflowing indices to wrap around rows
% You don't have to redefine "idx", could use this directly in the indexing line
idx = mod( idx + reshape(p,1,1,3) - 1, nz ) + 1;
% Output B. The "+ ... " is to convert to linear indices, as "idx"
% currently just refers to the row number.

INDICES = ((idx-1) * (nr*nc)+1 )+ reshape(0:1:nc*nr-1,nr,nc);

B = A(INDICES);
</code>```

Body:
i have a quite complicated question here which i am working on. It's extremely difficult to describe in words, so i will try to explain it with an example.

Assume i have a matrix of values:

A =

[31 85 36 71 51]
[12 33 74 39 12]
[67 11 13 14 18]
[35 36 84 33 57]

Now, i want to first find a maximum vector in the first dimension, which is easy:

[max_vector,~] = max(A,[],1);

max_vector=[67,85, 84, 71,57]

Now i want to get a "slimmed" matrix with values around the maxima (periodical indices):

Desired_Matrix =

 [12 36 36 33 18]
 [67 85 84 71 57]
 [35 33 13 39 51]

This is the matrix with the vectors around the maximum values of matrix A. Can someone tell me how to do this without using a double for loop?

Thank you!

Body:
just for your information, here is the generalized form for the 3D-Case:

A = zeros(3,5,5);

for id = 1: 20
    A(:,:,id) = id;

    if id == 10
        A(:,:,id) = 100;
    end

end

% Relative rows of neighbours, i.e. this is [-1, 0, 1] for +/- one row
p = -1:1;
% Get A row and column counts for ease
[nr, nc, nz] = size(A);
% Get max indices
[~,idx] = max( A, [], 3 );
% Handle overflowing indices to wrap around rows
% You don't have to redefine "idx", could use this directly in the indexing line
idx = mod( idx + reshape(p,1,1,3) - 1, nz ) + 1;
% Output B. The "+ ... " is to convert to linear indices, as "idx"
% currently just refers to the row number.

INDICES = ((idx-1) * (nr*nc)+1 )+ reshape(0:1:nc*nr-1,nr,nc);

B = A(INDICES);


问:
Check if at least two elements in an array are greater than zero - JavaScript/Typescript
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

```<code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

</code>```

答:
If you are in a situation where doing things like this is frequently necessary, you can always create your own facility for producing predicate functions. In this case, you could start with a master function to create functions that return true or false if an array contains a minimum number of values that satisfy a condition:

```<code>function minimumSatisfy(condition, minimum) {
  return function(array) {
    for (var i = 0, c = 0; i < array.length && c < minimum; i++) {
      if (condition(array[i]))
        c++;
    }
    return c >= minimum;
  }
}
</code>```

To use that for checking your particular case, use it to make a specific function:

```<code>let twoGtZero = minimumSatisfy(v => v > 0, 2);
</code>```

Now you can test any array with that predicate:

```<code>if (twoGtZero(someArray)) {
  // ...
}
</code>```

Of course if you've only got one place in your code that requires such a test, it would be silly to do this.

Body:
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

Body:
If you are in a situation where doing things like this is frequently necessary, you can always create your own facility for producing predicate functions. In this case, you could start with a master function to create functions that return true or false if an array contains a minimum number of values that satisfy a condition:

function minimumSatisfy(condition, minimum) {
  return function(array) {
    for (var i = 0, c = 0; i < array.length && c < minimum; i++) {
      if (condition(array[i]))
        c++;
    }
    return c >= minimum;
  }
}

To use that for checking your particular case, use it to make a specific function:

let twoGtZero = minimumSatisfy(v => v > 0, 2);

Now you can test any array with that predicate:

if (twoGtZero(someArray)) {
  // ...
}

Of course if you've only got one place in your code that requires such a test, it would be silly to do this.


问:
.Include only loading first instance of included entity
I am trying to load a reward with it's information.  I am using the following code:

```<code>var rewards = await ctx.RewardGroupRewards.Where(r => r.CampaignRewardGroup.Id == rewardGroupId)
                .Include(r => r.CampaignRewardGroup)
                .Include(r => r.CampaignRewardCategory)
                .Include(r => r.CostDenomination)
                .Include(r => r.Reward)
                .ToListAsync();
</code>```

When I inspect the result in the debugger, the first item in the list is loaded correctly but the second item in the list has been loaded with what you'd get if you created a new group, even though its group Id is set correctly (or it wouldn't appear in the results at all).

答:
Just in case this is useful for anyone, I found a solution to this.

I installed the EntityFrameworkCore.Proxies package and enabled lazy loading, as described here (https://dotnetcoretutorials.com/2019/09/07/lazy-loading-with-ef-core/).  This gave some errors for mapping properties which were not virtual (although not the ones used in the specific query above).  Once I'd fixed that, everything worked.

The weird thing is, it now works with lazy loading off as well so it could be enough to just add the Proxies reference to the project or make sure all your navigation properties are virtualised, but I'm going to leave LL on anyway as it makes sense for my project.

Body:
I am trying to load a reward with it's information.  I am using the following code:

var rewards = await ctx.RewardGroupRewards.Where(r => r.CampaignRewardGroup.Id == rewardGroupId)
                .Include(r => r.CampaignRewardGroup)
                .Include(r => r.CampaignRewardCategory)
                .Include(r => r.CostDenomination)
                .Include(r => r.Reward)
                .ToListAsync();

When I inspect the result in the debugger, the first item in the list is loaded correctly but the second item in the list has been loaded with what you'd get if you created a new group, even though its group Id is set correctly (or it wouldn't appear in the results at all).


问:
How to check Postgres backup has been successful(Without manual efforts)?
We have 100+ databases contains daily backups

how to check failure backups in PostgreSQL backup schedules

pg_dump -h localhost -p 5432  -U postgres -d db1  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db2  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db3  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db4  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db5  -v -f "path/file.backup"
...
```

like this i have 100 backup schedules

答:
Try to do it in for loop for example?

```<code>#!/bin/bash

# create an indexed array with all your databases listed
database_names=( "1" "2" "3" )

# Declare an associative array to store dbname and dump status codes
declare -A all_dbdump_states

for db in "${database_names[@]}"; do
   echo "Executing $db dump.."
   pg_dump -h localhost -p 5432 -U postgres -d $db -v -f "path/file.backup"
   dump_rc=$? # Save exit code of pg_dump process into variable

   # After each for loop iteration, append data into array
   all_dbdump_states[$db]+=$dump_rc
done

echo -e "\nListing status codes of all dumps:"
for db in "${!all_dbdump_states[@]}"; do
   echo "Database [$db] status: ${all_dbdump_states[$db]}"
   sleep 1
done
</code>```

Here I'm echoing these pg_dump lines for better tests and made an explicit mistake in echo command to put second command fail, with exit code 127:

```<code>#!/bin/bash

# create an indexed array with all your databases listed
database_names=( "1" "2" "3" )

# Declare an assotiative array to store dbname and dump status codes
declare -A all_dbdump_states

for db in "${database_names[@]}"; do
   echo "Executing $db dump.."
   if [[ $db -eq 2 ]]; then
      ech "pg_dump -h localhost -p 5432 -U postgres -d 2 -v -f 'path/file.backup'" &>/dev/null
      dump_rc=$? # Save exit code of pg_dump process into variable
      all_dbdump_states[$db]+=$dump_rc
      continue
   fi
   echo "pg_dump -h localhost -p 5432 -U postgres -d $db -v -f 'path/file.backup'" &>/dev/null
   dump_rc=$? # Save exit code of pg_dump process into variable

   # After each for loop iteration, append data into array
   all_dbdump_states[$db]+=$dump_rc
done

echo -e "\nListing status codes of all dumps:"
for db in "${!all_dbdump_states[@]}"; do
   echo "Database [$db] status: ${all_dbdump_states[$db]}"
   sleep 1
done
</code>```

Sample output:

```<code>$ ./test.sh
Executing 1 dump..
Executing 2 dump..
Executing 3 dump..

Listing status codes of all dumps:
Database [1] status: 0
Database [2] status: 127
Database [3] status: 0
</code>```

Body:
We have 100+ databases contains daily backups

how to check failure backups in PostgreSQL backup schedules

pg_dump -h localhost -p 5432  -U postgres -d db1  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db2  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db3  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db4  -v -f "path/file.backup"
pg_dump -h localhost -p 5432  -U postgres -d db5  -v -f "path/file.backup"
...

like this i have 100 backup schedules

Body:
Try to do it in for loop for example?

#!/bin/bash

# create an indexed array with all your databases listed
database_names=( "1" "2" "3" )

# Declare an associative array to store dbname and dump status codes
declare -A all_dbdump_states

for db in "${database_names[@]}"; do
   echo "Executing $db dump.."
   pg_dump -h localhost -p 5432 -U postgres -d $db -v -f "path/file.backup"
   dump_rc=$? # Save exit code of pg_dump process into variable

   # After each for loop iteration, append data into array
   all_dbdump_states[$db]+=$dump_rc
done

echo -e "\nListing status codes of all dumps:"
for db in "${!all_dbdump_states[@]}"; do
   echo "Database [$db] status: ${all_dbdump_states[$db]}"
   sleep 1
done

Here I'm echoing these pg_dump lines for better tests and made an explicit mistake in echo command to put second command fail, with exit code 127:

#!/bin/bash

# create an indexed array with all your databases listed
database_names=( "1" "2" "3" )

# Declare an assotiative array to store dbname and dump status codes
declare -A all_dbdump_states

for db in "${database_names[@]}"; do
   echo "Executing $db dump.."
   if [[ $db -eq 2 ]]; then
      ech "pg_dump -h localhost -p 5432 -U postgres -d 2 -v -f 'path/file.backup'" &>/dev/null
      dump_rc=$? # Save exit code of pg_dump process into variable
      all_dbdump_states[$db]+=$dump_rc
      continue
   fi
   echo "pg_dump -h localhost -p 5432 -U postgres -d $db -v -f 'path/file.backup'" &>/dev/null
   dump_rc=$? # Save exit code of pg_dump process into variable

   # After each for loop iteration, append data into array
   all_dbdump_states[$db]+=$dump_rc
done

echo -e "\nListing status codes of all dumps:"
for db in "${!all_dbdump_states[@]}"; do
   echo "Database [$db] status: ${all_dbdump_states[$db]}"
   sleep 1
done

Sample output:

$ ./test.sh
Executing 1 dump..
Executing 2 dump..
Executing 3 dump..

Listing status codes of all dumps:
Database [1] status: 0
Database [2] status: 127
Database [3] status: 0


问:
How do I add a selector or function delegate as a member of a struct?
For each item in a list of Item I want to specify a function member like let function: ??? where its type will allow me to assign a function like open(Item)

```<code>struct Item {
    let label: String
    let roomID: Int
    let function: ??? <- what can I say here that takes a function like open(Item)
}
</code>```

EDIT: Here I'm trying the (Item) -> Void. But I'm getting this error: '(MyClass) -> (MyClass.Item) -> Void' is not convertible to '(MyClass.Item) -> Void'

```<code>let tabTwoItems = [
    Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}

func tabTwoFunction(_ item: Item) -> Void {

}
</code>```

答:
```<code>struct Item {
    let label: String
    let roomID: Int
    let function: (Item) -> Void
}
</code>```

but more efficient is using protocols:

```<code>protocol ItemDelegate {
    func call(item: Item)
}

struct Item {
    let label: String
    let roomID: Int
    let itemDelegate: ItemDelegate
}
</code>```

The second solution may lay in the stack. It has more performance.

For global methods use enum namespaces:

The problem in your playground that tabTwoFunction is declared too late. In order to fix it, wrap it my namespace:

```<code>enum NameSpace {

static func tabTwoFunction(_ item: Item) -> Void {

}

static let tabTwoItems = [
    NameSpace.Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}
}
</code>```

Body:
For each item in a list of Item I want to specify a function member like let function: ??? where its type will allow me to assign a function like open(Item)

struct Item {
    let label: String
    let roomID: Int
    let function: ??? <- what can I say here that takes a function like open(Item)
}

EDIT: Here I'm trying the (Item) -> Void. But I'm getting this error: '(MyClass) -> (MyClass.Item) -> Void' is not convertible to '(MyClass.Item) -> Void'

let tabTwoItems = [
    Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}

func tabTwoFunction(_ item: Item) -> Void {

}

Body:
struct Item {
    let label: String
    let roomID: Int
    let function: (Item) -> Void
}

but more efficient is using protocols:

protocol ItemDelegate {
    func call(item: Item)
}

struct Item {
    let label: String
    let roomID: Int
    let itemDelegate: ItemDelegate
}

The second solution may lay in the stack. It has more performance.

For global methods use enum namespaces:

The problem in your playground that tabTwoFunction is declared too late. In order to fix it, wrap it my namespace:

enum NameSpace {

static func tabTwoFunction(_ item: Item) -> Void {

}

static let tabTwoItems = [
    NameSpace.Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}
}


问:
Having unique random numbers in more than one variables
Is it possible to have more than one variables and each have a unique and distinct random number from one another. The sample range is the same, yet I do not want the variables to have same numbers.

```<code>import random

A=random.sample(range(1,4),1)
B=random.sample(range(1,4),1)
C=random.sample(range(1,4),1)
</code>```

So the above example, I want A, B and C to have different random numbers. In other words, no two variables must have the same number.

How to go about this?

答:
You can do

```<code>y = range(1, 4)
x = np.random.choice(y, 3, replace=False)
print(x)
</code>```

[2 1 3]

Body:
Is it possible to have more than one variables and each have a unique and distinct random number from one another. The sample range is the same, yet I do not want the variables to have same numbers.

import random

A=random.sample(range(1,4),1)
B=random.sample(range(1,4),1)
C=random.sample(range(1,4),1)

So the above example, I want A, B and C to have different random numbers. In other words, no two variables must have the same number.

How to go about this?

Body:
You can do

y = range(1, 4)
x = np.random.choice(y, 3, replace=False)
print(x)

[2 1 3]


问:
How to increment div id with php for loop?
I have the following div. I would like to have mydiv1, mydiv2 and mydiv3. Is this possible to do?

Code:

```<code><?php for($i =1; $i <3; $i++):?>
    <div id="mydiv<?php $i?>" style="float:left">
<?php endfor;?>
</code>```

答:
You don't need the inner for loop (3 x 3 = 9).  You simply need a counter that you increment on each iteration of the outer loop:

```<code><?php

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

$counter = 1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$counter .'">'. $v .'<div>';
    $counter++;
}
</code>```

Body:
I have the following div. I would like to have mydiv1, mydiv2 and mydiv3. Is this possible to do?

Code:

<?php for($i =1; $i <3; $i++):?>
    <div id="mydiv<?php $i?>" style="float:left">
<?php endfor;?>

Body:
You don't need the inner for loop (3 x 3 = 9).  You simply need a counter that you increment on each iteration of the outer loop:

<?php

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

$counter = 1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$counter .'">'. $v .'<div>';
    $counter++;
}


问:
How to call browser back button in Angular Project
In my Angular 8 project, I currently have a landing page (template-table.component) that shows a list of items that can be filtered and sorted. The filter and sort are added to the route queryParams(ex: "/template-table?name=another&type=Type%201"). If you select an item in the list, you will be taken to another route (that has the template-details.component) that has more details on that item. This details page will have a 'back to list' button that should take the user back to their previous list page.

Since I want the user to be taken back to the list with the filter params they were previously  using, I can't simply go to the route of that component, instead I want to go back in history (like how the browser back button works). So, how do I set an element to link to what the browser back button would be link to?

So, this is the bare minimum of my template-detail.component.html:

```<code><h1>template-details works!</h1>
<div>{{template}}</div>
<div>{{id}}</div>
<div><a routerLink="/template-table/">Return to list page</a></div>
</code>```

I think I also would like to check the route to see if it's the template-table component route with query params, and not an unrelated route. (So, the route would need to be like: "/template-table?params=xxx", and couldn't be "google.com". If the browser back button isn't related to the template-table, then it should go to "/template-table" without any params (or maybe my 404 page.)

The basic functionality that I'm wanting to achieve is for the user to be able to filter a list, go to another route with more info on a list item, and then return to the list with the same filters they previously added. If there would be a better way to do this than by trying to access the browser's back button, I'd love to hear about it.

Thank you for any assistance you can provide.

答:
Something like that should work:
 routerLink="../"

But you can solve this problem in an elegant way thanks to the location of the library. Check out this post: enter link description here

Body:
In my Angular 8 project, I currently have a landing page (template-table.component) that shows a list of items that can be filtered and sorted. The filter and sort are added to the route queryParams(ex: "/template-table?name=another&type=Type%201"). If you select an item in the list, you will be taken to another route (that has the template-details.component) that has more details on that item. This details page will have a 'back to list' button that should take the user back to their previous list page.

Since I want the user to be taken back to the list with the filter params they were previously  using, I can't simply go to the route of that component, instead I want to go back in history (like how the browser back button works). So, how do I set an element to link to what the browser back button would be link to?

So, this is the bare minimum of my template-detail.component.html:

template-details works!

{{template}}

{{id}}

Return to list page

I think I also would like to check the route to see if it's the template-table component route with query params, and not an unrelated route. (So, the route would need to be like: "/template-table?params=xxx", and couldn't be "google.com". If the browser back button isn't related to the template-table, then it should go to "/template-table" without any params (or maybe my 404 page.)

The basic functionality that I'm wanting to achieve is for the user to be able to filter a list, go to another route with more info on a list item, and then return to the list with the same filters they previously added. If there would be a better way to do this than by trying to access the browser's back button, I'd love to hear about it.

Thank you for any assistance you can provide.


问:
Blank page after logging in
i'm trying to create a login/register system with PDO and sessions and a user can create his account and he ca access the Welcome page , but when logging out and trying to log back with working username and password , it sends me to a blank php page , i looked on the internet and a blank php page means syntax error which i can't find any.
Btw i tried typing any username with any password and it stills sending me to a blank php page
here's my code :
Config.php

```<code>class config {

    public static function connect()
    {
        $host = "localhost";
        $username = "root";
        $password = "";
        $dbname = "logintest";

        try{

            $bdd = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);

            $bdd->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

        }catch(PDOException $e)
        {
            echo "Connection échoué" . $e->getMessage();
        }
        return $bdd;
    }
}

?>
</code>```

My process.php (that's where i think the probleme is comming from :

```<code>
session_start();

    include_once("config.php");

        if(isset($_POST['register']))
        {
            $bdd = config::connect();
            $username = $_POST['username'];
            $email = $_POST['email'];
            $password = $_POST['password'];

    if(insertDetails($bdd,$username,$email,$password))
    {
        $_SESSION['username'] = $username;
        header("Location: profile.php");
    }

}

    if(isset($_POST['login']))
    {
        $bdd = config::connect();
        $username = $_POST['username'];
        $password = $_POST['password'];

    if(checkLogin($bdd,$username,$password))
        {
            $_SESSION['username'] = $username;
            header("Location: profile.php");
        }
    else{
        echo "Le mot de passe ou le nom d'utilisateur sont incorrect";
    }
}

    function insertDetails($bdd,$username,$email,$password)
        {
            $query = $bdd->prepare("

                INSERT INTO users (username,email,password)

                VALUES(:username,:email,:password)

                ");
            $query->bindParam(":username",$username);
            $query->bindParam(":email",$email);
            $query->bindParam(":password",$password);

    return $query->execute();
}

    function checkLogin($bdd,$username,$password)
    {
        $query = $bdd->prepare("

            SELECT * From users WHERE username=:username AND password=:password

        ");

        $query->bindParam(":username", $username);
        $query->bindParam(":password", $password);

        $query->execute();

    // Check how many rows are returned

        if ($query->rowCount() == 1)
        {
            return true;
        }
        else {
            return false;
        }

    }

</code>```

my profile.php :

```<code>session_start();

include_once("config.php");

echo "Bienvenue " . $_SESSION['username'] . "  ";

echo "<a href='logout.php'>Se deconnecter</a>". "  ";

echo "<a href='update.php'>Mettre a jour le profile</a>" . "  ";

echo "<a href='delete.php'>Supprimer mon compte</a>". "  ";

?>```
and my logout.php :
```<?php

session_destroy();

header("Location: index.html");
?>
</code>```

Or here's the project i'm working on : https://github.com/AmrouHab/LoginRegister/tree/master/neptunetest

I'll take any help
Thanks
(Btw sorry for my bad english im french)

答:
Well , i found the solution
I forgot to put an uppercase "L" in process.php

```<code> if(isset($_POST['login']))
</code>```

I've corrected it to

```<code> if(isset($_POST['Login']))
</code>```

and now it's working.
Thanks for your attention.

Title: Blank page after logging in

Body:
i'm trying to create a login/register system with PDO and sessions and a user can create his account and he ca access the Welcome page , but when logging out and trying to log back with working username and password , it sends me to a blank php page , i looked on the internet and a blank php page means syntax error which i can't find any.
Btw i tried typing any username with any password and it stills sending me to a blank php page
here's my code :
Config.php

class config {

    public static function connect()
    {
        $host = "localhost";
        $username = "root";
        $password = "";
        $dbname = "logintest";

        try{

            $bdd = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);

            $bdd->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

        }catch(PDOException $e)
        {
            echo "Connection échoué" . $e->getMessage();
        }
        return $bdd;
    }
}

?>

My process.php (that's where i think the probleme is comming from :

session_start();

    include_once("config.php");

        if(isset($_POST['register']))
        {
            $bdd = config::connect();
            $username = $_POST['username'];
            $email = $_POST['email'];
            $password = $_POST['password'];

    if(insertDetails($bdd,$username,$email,$password))
    {
        $_SESSION['username'] = $username;
        header("Location: profile.php");
    }

}

    if(isset($_POST['login']))
    {
        $bdd = config::connect();
        $username = $_POST['username'];
        $password = $_POST['password'];

    if(checkLogin($bdd,$username,$password))
        {
            $_SESSION['username'] = $username;
            header("Location: profile.php");
        }
    else{
        echo "Le mot de passe ou le nom d'utilisateur sont incorrect";
    }
}

    function insertDetails($bdd,$username,$email,$password)
        {
            $query = $bdd->prepare("

                INSERT INTO users (username,email,password)

                VALUES(:username,:email,:password)

                ");
            $query->bindParam(":username",$username);
            $query->bindParam(":email",$email);
            $query->bindParam(":password",$password);

    return $query->execute();
}

    function checkLogin($bdd,$username,$password)
    {
        $query = $bdd->prepare("

            SELECT * From users WHERE username=:username AND password=:password

        ");

        $query->bindParam(":username", $username);
        $query->bindParam(":password", $password);

        $query->execute();

    // Check how many rows are returned

        if ($query->rowCount() == 1)
        {
            return true;
        }
        else {
            return false;
        }

    }

my profile.php :

session_start();

include_once("config.php");

echo "Bienvenue " . $_SESSION['username'] . "  ";

echo "Se deconnecter". "  ";

echo "Mettre a jour le profile" . "  ";

echo "Supprimer mon compte". "  ";

?>```
and my logout.php :
```<?php

session_destroy();

header("Location: index.html");
?>

Or here's the project i'm working on : https://github.com/AmrouHab/LoginRegister/tree/master/neptunetest

I'll take any help
Thanks
(Btw sorry for my bad english im french)

Body:
Well , i found the solution
I forgot to put an uppercase "L" in process.php

 if(isset($_POST['login']))

I've corrected it to

 if(isset($_POST['Login']))

and now it's working.
Thanks for your attention.


问:
Why does deleting "A=[13,20,7,12,10,2,5,1,0,18]" in line 7 of my program change the print(D) in the end?
Keeping or deleting line 7 in my program should not change the output, because I will only be assigning the same value to "A" twice. But deleting it changes the output. Here is the code

```<code>def C(A):
    A[1]=A[8]+A[4]
    return A
D=[]
A=[13,20,7,12,10,2,5,1,0,18]
Z=A
A=[13,20,7,12,10,2,5,1,0,18]  #When I delete this line, print(D) in the end gives different value .
A[9]=A[3]-A[0]
if A[9]>0:
         A[2] = A[9] * A[1]
else:
    C(A)
    if A[1]>A[6]:
        A[2]=A[9]*A[1]
    else:
         while 2>1:
             C(A)
             if A[1]>A[6]:
                 A[2]=A[9]*A[1]
                 break
for x in range(0,len(A)):
    if (Z[x] == A[x]):
      D.append(A[x])
print(D)
</code>```

If it is related to shallow memory Why does this code give the same output even when I delete line 3?

```<code>A=[13,20,7,12,10,2,5,1,0,18]
Z=A
A=[1,1,1,1,1,1,1,1,1,1]
print(Z)
</code>```

答:
This shows the ID's of each variable through the assignments.

```<code>>>> A = [1,2,3]
>>> id(A)
19812552
>>> Z=A
>>> id(Z)
19812552
>>> id(A)
19812552
>>> A = [1,2,3]
>>> id(A)
19917160
>>> id(Z)
19812552
</code>```

As you can see, when you reassign A to what it previously was it changes the address meaning it is no longer a shallow copy of Z, but rather a completely new list.

For the second part of the question, let's take 2 addresses (X and Y) and 2 variables (A and B):

```<code>A = [1,2,3] ( A now points to address X)
B = A (Z points to the same address as A, Z points to X)
A = [1,1,1] (A is now stored in a new address, address Y, B/X unchanged)
</code>```

The second line causes no change to the variable B, so if you delete line 3, there is no change to the output.

Body:
Keeping or deleting line 7 in my program should not change the output, because I will only be assigning the same value to "A" twice. But deleting it changes the output. Here is the code

def C(A):
    A[1]=A[8]+A[4]
    return A
D=[]
A=[13,20,7,12,10,2,5,1,0,18]
Z=A
A=[13,20,7,12,10,2,5,1,0,18]  #When I delete this line, print(D) in the end gives different value .
A[9]=A[3]-A[0]
if A[9]>0:
         A[2] = A[9] * A[1]
else:
    C(A)
    if A[1]>A[6]:
        A[2]=A[9]*A[1]
    else:
         while 2>1:
             C(A)
             if A[1]>A[6]:
                 A[2]=A[9]*A[1]
                 break
for x in range(0,len(A)):
    if (Z[x] == A[x]):
      D.append(A[x])
print(D)

If it is related to shallow memory Why does this code give the same output even when I delete line 3?

A=[13,20,7,12,10,2,5,1,0,18]
Z=A
A=[1,1,1,1,1,1,1,1,1,1]
print(Z)

Body:
This shows the ID's of each variable through the assignments.

>>> A = [1,2,3]
>>> id(A)
19812552
>>> Z=A
>>> id(Z)
19812552
>>> id(A)
19812552
>>> A = [1,2,3]
>>> id(A)
19917160
>>> id(Z)
19812552

As you can see, when you reassign A to what it previously was it changes the address meaning it is no longer a shallow copy of Z, but rather a completely new list.

For the second part of the question, let's take 2 addresses (X and Y) and 2 variables (A and B):

A = [1,2,3] ( A now points to address X)
B = A (Z points to the same address as A, Z points to X)
A = [1,1,1] (A is now stored in a new address, address Y, B/X unchanged)

The second line causes no change to the variable B, so if you delete line 3, there is no change to the output.


问:
Using of SQLite TypeError: Cannot read property 'transaction' of null
I use ionic4 + angular8 code flow:

Error code:

Please help me. Thank you.

error code in here
enter image description here

答:
You have written transaction but, I let you know that there is no property of transaction in SQLite plugin, you need to add write create property, whatever to open or create the database. like =>

```<code>this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) =>

db.executeSql('create table danceMoves(name VARCHAR(32))', [])
  .then(() => console.log('Executed SQL'))
  .catch(e => console.log(e));
  })

  .catch(e => console.log(e));
</code>```

Body:
You have written transaction but, I let you know that there is no property of transaction in SQLite plugin, you need to add write create property, whatever to open or create the database. like =>

this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) =>

db.executeSql('create table danceMoves(name VARCHAR(32))', [])
  .then(() => console.log('Executed SQL'))
  .catch(e => console.log(e));
  })

  .catch(e => console.log(e));


问:
recyclerview inside nested scroll view is not scolling
I have a recyclerview inside a nestedScrollView and I have stopped the scrolling of recyclerview to allow nestedScrollView to scroll all the page, but the nestedScrollView is not working.

I have set the nestedScrollingEnabled of the recyclerview to false

I have tried to add a hidden view under the recyclerview but it has shown on top of the bottom items of recyclerview

My layout xml file code is:

```<code><?xml version="1.0" encoding="utf-8"?>

<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="viewModel"
        type="com.accad.accadgame.viewmodels.profile.ProfileViewModel" />
</data>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/circleImageView"
            android:layout_width="75dp"
            android:layout_height="0dp"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginTop="@dimen/default_xxdim"
            android:layout_marginEnd="@dimen/default_dim"
            android:src="@drawable/profile"
            app:layout_constraintDimensionRatio="h,1:1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/profile_name"
            style="@style/HeadlineTextViewActiveStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_dim"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginEnd="@dimen/default_dim"
            android:text="@{viewModel.profileName}"
            app:layout_constraintEnd_toEndOf="@+id/circleImageView"
            app:layout_constraintStart_toStartOf="@+id/circleImageView"
            app:layout_constraintTop_toBottomOf="@+id/circleImageView"
            tools:text="@tools:sample/lorem" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/profile_details_list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/default_xxdim"
            android:clipToPadding="false"
            android:paddingBottom="@dimen/default_dim"
            android:paddingStart="@dimen/default_dim"
            android:nestedScrollingEnabled="false"
            app:layout_constraintBottom_toBottomOf="parent"
            android:focusable="false"
            app:layout_constraintTop_toBottomOf="@id/profile_name"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>
</code>```

答:
After many tries, I've found the solution

which is to change the recyclerView's height to be wrap_content instead of match_parent or 0dp so the recyclerView would be like this:

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/profile_details_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/default_xxdim"
        android:clipToPadding="false"
        android:paddingBottom="@dimen/default_dim"
        android:paddingStart="@dimen/default_dim"
        android:nestedScrollingEnabled="false"
        app:layout_constraintBottom_toBottomOf="parent"
        android:focusable="false"
        app:layout_constraintTop_toBottomOf="@id/profile_name"
        />
</code>```

Body:
I have a recyclerview inside a nestedScrollView and I have stopped the scrolling of recyclerview to allow nestedScrollView to scroll all the page, but the nestedScrollView is not working.

I have set the nestedScrollingEnabled of the recyclerview to false

I have tried to add a hidden view under the recyclerview but it has shown on top of the bottom items of recyclerview

My layout xml file code is:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="viewModel"
        type="com.accad.accadgame.viewmodels.profile.ProfileViewModel" />
</data>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/circleImageView"
            android:layout_width="75dp"
            android:layout_height="0dp"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginTop="@dimen/default_xxdim"
            android:layout_marginEnd="@dimen/default_dim"
            android:src="@drawable/profile"
            app:layout_constraintDimensionRatio="h,1:1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/profile_name"
            style="@style/HeadlineTextViewActiveStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_dim"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginEnd="@dimen/default_dim"
            android:text="@{viewModel.profileName}"
            app:layout_constraintEnd_toEndOf="@+id/circleImageView"
            app:layout_constraintStart_toStartOf="@+id/circleImageView"
            app:layout_constraintTop_toBottomOf="@+id/circleImageView"
            tools:text="@tools:sample/lorem" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/profile_details_list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/default_xxdim"
            android:clipToPadding="false"
            android:paddingBottom="@dimen/default_dim"
            android:paddingStart="@dimen/default_dim"
            android:nestedScrollingEnabled="false"
            app:layout_constraintBottom_toBottomOf="parent"
            android:focusable="false"
            app:layout_constraintTop_toBottomOf="@id/profile_name"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

Body:
After many tries, I've found the solution

which is to change the recyclerView's height to be wrap_content instead of match_parent or 0dp so the recyclerView would be like this:

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/profile_details_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/default_xxdim"
        android:clipToPadding="false"
        android:paddingBottom="@dimen/default_dim"
        android:paddingStart="@dimen/default_dim"
        android:nestedScrollingEnabled="false"
        app:layout_constraintBottom_toBottomOf="parent"
        android:focusable="false"
        app:layout_constraintTop_toBottomOf="@id/profile_name"
        />


问:
Cut out a sequence of files using glob in python
I have a directory with files like img-0001.jpg, img-0005.pg, img-0006.jpg, ... , img-xxxx.jpg.
What I need to do is to get a list with all files starting at 0238, literally img-0238.jpg. The next existing filename is img-0240.jpg

Right now I use glob to get all filenames.

```<code>list_images = glob.glob(path_images + "*.jpg")
</code>```

Thanks in advance

Edit:

-> The last filename is img-0315.jpg

答:
Glob doesn't allow regex filtering. But you filter list right after you receive all matching files.
Here is how it would look like using re:

```<code>import re

list_images = [f for f in glob.glob(path_images + "*.jpg") \
    if re.search(r'[1-9]\d{3,}|0[3-9]\d{2,}|02[4-9]\d|023[8-9]\.jpg$', f)]
</code>```

The regular expression with verify that file ends with number with 4 digits bigger or equal 0238.

You can play around with regular expression using https://regex101.com/

Basically, we check if number is:

starts with 1 followed by any 3 digits

or starts with 0[3-9] followed by any 2 digits

or starts with 02[4-9] followed by any 1 digit

or starts with 023 and followed by either 8 or 9.

But it's probably would be easier to do simple comparison:

```<code>list_images = [f for f in glob.glob(path_images + "*.jpg") \
     if f[-8:-4] > "0237" and f[-8:-4] < "0316"]
</code>```

Body:
I have a directory with files like img-0001.jpg, img-0005.pg, img-0006.jpg, ... , img-xxxx.jpg.
What I need to do is to get a list with all files starting at 0238, literally img-0238.jpg. The next existing filename is img-0240.jpg

Right now I use glob to get all filenames.

list_images = glob.glob(path_images + "*.jpg")

Thanks in advance

Edit:

-> The last filename is img-0315.jpg

Body:
Glob doesn't allow regex filtering. But you filter list right after you receive all matching files.
Here is how it would look like using re:

import re

list_images = [f for f in glob.glob(path_images + "*.jpg") \
    if re.search(r'[1-9]\d{3,}|0[3-9]\d{2,}|02[4-9]\d|023[8-9]\.jpg$', f)]

The regular expression with verify that file ends with number with 4 digits bigger or equal 0238.

You can play around with regular expression using https://regex101.com/

Basically, we check if number is:

starts with 1 followed by any 3 digits

or starts with 0[3-9] followed by any 2 digits

or starts with 02[4-9] followed by any 1 digit

or starts with 023 and followed by either 8 or 9.

But it's probably would be easier to do simple comparison:

list_images = [f for f in glob.glob(path_images + "*.jpg") \
     if f[-8:-4] > "0237" and f[-8:-4] < "0316"]


问:
Can I delete rows using user defined functions in oracle?
I created a user defined function to delete some data. It doesn't work with delete but works with select. I am Oracle 9i.

The function is something like this:

```<code>create or replace function UFN_PURGEDATA(INPUTID IN VarChar2) return number is
  Result number;
begin

  Result := 0;

   DELETE FROM MyTable WHERE MyTable.ID=INPID;

  COMMIT;

   Result := 1;
 EXCEPTION WHEN OTHERS THEN

  return(Result);
end UFN_PURGEDATA;
</code>```

Then I use select UFN_PURGEDATA('test') from dual to run it but got result 0.

答:
You can perform DML inside a function used in a SELECT if you add PRAGMA AUTONOMOUS_TRANSACTION.  For example:

```<code>create or replace function UFN_PURGEDATA(INPUTID IN VarChar2) return number is
    pragma autonomous_transaction;
begin
  DELETE FROM MyTable WHERE MyTable.ID=INPUTID;
  COMMIT;
  return 1;
  EXCEPTION WHEN OTHERS THEN
  return 0;
end UFN_PURGEDATA;
/
</code>```

But you definitely want to avoid this approach if possible.  In general, there's no way to know how many times a function will be executed if it's used in a SELECT.

Body:
I created a user defined function to delete some data. It doesn't work with delete but works with select. I am Oracle 9i.

The function is something like this:

create or replace function UFN_PURGEDATA(INPUTID IN VarChar2) return number is
  Result number;
begin

  Result := 0;

   DELETE FROM MyTable WHERE MyTable.ID=INPID;

  COMMIT;

   Result := 1;
 EXCEPTION WHEN OTHERS THEN

  return(Result);
end UFN_PURGEDATA;

Then I use select UFN_PURGEDATA('test') from dual to run it but got result 0.

Body:
You can perform DML inside a function used in a SELECT if you add PRAGMA AUTONOMOUS_TRANSACTION.  For example:

create or replace function UFN_PURGEDATA(INPUTID IN VarChar2) return number is
    pragma autonomous_transaction;
begin
  DELETE FROM MyTable WHERE MyTable.ID=INPUTID;
  COMMIT;
  return 1;
  EXCEPTION WHEN OTHERS THEN
  return 0;
end UFN_PURGEDATA;
/

But you definitely want to avoid this approach if possible.  In general, there's no way to know how many times a function will be executed if it's used in a SELECT.


问:
Service 'MongoDB Server'(MongoDB) failed to start.Verify that you have sufficient privileges to start system services
When I'm trying to install MongoDB Community edition on windows 8.1, I'm getting below error.

I tried most of the available solution from the internet but none of them worked.

答:
I rebooted my computer and chose the default path when installing:

```<code>C:\Program Files\MongoDB\Server\4.2\bin
</code>```

and it successfully installed.

Body:
I rebooted my computer and chose the default path when installing:

C:\Program Files\MongoDB\Server\4.2\bin

and it successfully installed.


问:
Android: Prevent data notifications from popping up on the screen when app is in the background
I'm sending data payloads through FCM and handling them in the onMessageReceived() method of FirebaseMessagingService. The problem is, when the app is in the background, the push notifications seem to be popping up each time the device handles them. I'd like them to be silent similar to how Android delivers notification payloads.

How do I make sure the notifications do not create this popup effect? I'm on Android 9.

Here's how the notification is generated on the client:

```<code>var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, myChannelId)
                              .SetContentTitle(title)
                              .SetContentText(body)
                              .SetSmallIcon(Resource.Mipmap.ic_launcher)
                              .SetAutoCancel(true)
                              .SetContentIntent(pendingIntent);
</code>```

and this is how it's notified:

```<code>if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
   notificationBuilder.SetChannelId(myChannelId);

var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(myId, notificationBuilder.Build());
</code>```

答:
Notifications will appear with a popup effect ('Heads Up') view like shown in the screenshot if you set the notification channel priority to IMPORTANCE_HIGH or above, so to stop that happening, you should ensure the channel priority is IMPORTANCE_DEFAULT or lower.

If you have other notifications that you do want to use the heads up view, then you should create a separate NotificationChannel for this notification. Note that notification channels appear as 'Categories' in the notification settings for your app, allowing the user to choose which kinds of notifications they want to see from you, and two notifications wanting a different priority is a good indicator that they should be in different categories

Body:
I'm sending data payloads through FCM and handling them in the onMessageReceived() method of FirebaseMessagingService. The problem is, when the app is in the background, the push notifications seem to be popping up each time the device handles them. I'd like them to be silent similar to how Android delivers notification payloads.

How do I make sure the notifications do not create this popup effect? I'm on Android 9.

Here's how the notification is generated on the client:

var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, myChannelId)
                              .SetContentTitle(title)
                              .SetContentText(body)
                              .SetSmallIcon(Resource.Mipmap.ic_launcher)
                              .SetAutoCancel(true)
                              .SetContentIntent(pendingIntent);

and this is how it's notified:

if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
   notificationBuilder.SetChannelId(myChannelId);

var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(myId, notificationBuilder.Build());


问:
PEM routines:PEM_read_bio:bad end line
I'm trying to parse the developer certificate in embedded.mobileprovision file. Firstly I use

security cms -D -i embedded.mobileprovision

to get the base64 developer certificate string.

Then I split the string every 64 characters and stored in a file named dev.cer.

Finally add -----BEGIN CERTIFICATE----- at the first line and -----END CERTIFICATE----- at the end of file.

On my mac computer, I right click the dev.cer file and the developer informations are all there. However, When I use openssl x509 -in dev.cer -text -noout, error comes out:

```<code>unable to load certificate
69721:error:0906D066:PEM routines:PEM_read_bio:bad end line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/pem/pem_lib.c:747:
</code>```

The dev.cer file is following:

```<code>-----BEGIN CERTIFICATE-----
MIIFljCCBH6gAwIBAgIIIP7GMO9cWzYwDQYJKoZIhvcNAQELBQAwgZYxCzAJBgNV
BAYTAlVTMRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBXb3Js
ZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29ybGR3
aWRlIERldmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkw
HhcNMTcwNDI5MDMzMDA4WhcNMTgwNDI5MDMzMDA4WjCBiTEaMBgGCgmSJomT8ixk
AQEMCk1ENFA0UTg1WlExMzAxBgNVBAMMKmlQaG9uZSBEZXZlbG9wZXI6IGFtbW1p
IGFtbW1pIChXM1BSS1JDVDRRKTETMBEGA1UECwwKVktRNTZVQ0c4ODEUMBIGA1UE
CgwLYW1tbWkgYW1tbWkxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAwudboPuPnImOssBCw9vISRnnivreVwOuDAu77u47zIU8uTag
bzktX6pF54YToSLQHeOaNNQfZ7idccU2DKVBr3etz/++ca4HNadeUaEm2VWW4kEq
3iKIo1wZZhJJR6bQl4q797U0+f7eEXLKD4fjfidEF+ceAxAsX5YIuokq3K/B+XW3
tKk7D4nCaaCyJ9/+aJkFKT/oOxWRD0NYi5vXpni/3Plj5Qu3kDGrTUQaGCXXjRrA
E3mOVS4M2W5sFoOUpBxcfK7ajs+HUZNp0Gvb04OeD4O0lLTxcNu6omhG3MzOo81F
T+bkdxLM7XkIbNlIjYhyxGRynpgAKmiR9B/oeQIDAQABo4IB8TCCAe0wPwYIKwYB
BQUHAQEEMzAxMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5hcHBsZS5jb20vb2Nz
cDAzLXd3ZHIwMTAdBgNVHQ4EFgQUF8T1dPnBmZfKfG0+lHtczMuGy9owDAYDVR0T
AQH/BAIwADAfBgNVHSMEGDAWgBSIJxcJqbYYYIvs67r2R1nFUlSjtzCCAR0GA1Ud
IASCARQwggEQMIIBDAYJKoZIhvdjZAUBMIH+MIHDBggrBgEFBQcCAjCBtgyBs1Jl
bGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMg
YWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1z
IGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBj
ZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMDYGCCsGAQUFBwIBFipo
dHRwOi8vd3d3LmFwcGxlLmNvbS9jZXJ0aWZpY2F0ZWF1dGhvcml0eS8wDgYDVR0P
AQH/BAQDAgeAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMDMBMGCiqGSIb3Y2QGAQIB
Af8EAgUAMA0GCSqGSIb3DQEBCwUAA4IBAQA1//RUQ+hnCxfzSKO13qtuSb4IUrY5
bjkRKIAUlxN5aYVN5NIzCGxmahlDA/Rjw8MLVA8dWbT0QMSqx5IXC+Ov3JNZlkL0
5+RBuZEtZL7IZp0L3ZrCFtuizaunH9fZWbyFyfLACIYqZqP40N1+wIx1l4Es65Zu
WSeDeQMutda8DpmtCJhrnod9B1vfvDc3FUSmbJbvkLFh2UCgqtE9moLYI8qFMzqe
CQUJdPGdE+2WNv0wM8/cFIG/audSvEADKg1DgO+j6oP+urUe1gLsyzyv10J7/XA4
nmDuP1UNG7O7ADbdEOxhRiB96ZNwgcw9Q0wv9H9jMa+NNti6SxLud2+B
-----END CERTIFICATE----
</code>```

By the way, I used online certificate decoder to decode dev.cer, it works well. Here is the url:

```<code>https://www.sslshopper.com/certificate-decoder.html
</code>```

This site recommended to use openssl, but it failed.

答:
Surprisingly I had a case when my chained certificate had such a silly mistake:

-----END CERTIFICATE----------BEGIN CERTIFICATE-----

instead of

-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----

Title: PEM routines:PEM_read_bio:bad end line

Body:
I'm trying to parse the developer certificate in embedded.mobileprovision file. Firstly I use

security cms -D -i embedded.mobileprovision

to get the base64 developer certificate string.

Then I split the string every 64 characters and stored in a file named dev.cer.

Finally add -----BEGIN CERTIFICATE----- at the first line and -----END CERTIFICATE----- at the end of file.

On my mac computer, I right click the dev.cer file and the developer informations are all there. However, When I use openssl x509 -in dev.cer -text -noout, error comes out:

unable to load certificate
69721:error:0906D066:PEM routines:PEM_read_bio:bad end line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/pem/pem_lib.c:747:

The dev.cer file is following:

-----BEGIN CERTIFICATE-----
MIIFljCCBH6gAwIBAgIIIP7GMO9cWzYwDQYJKoZIhvcNAQELBQAwgZYxCzAJBgNV
BAYTAlVTMRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBXb3Js
ZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29ybGR3
aWRlIERldmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkw
HhcNMTcwNDI5MDMzMDA4WhcNMTgwNDI5MDMzMDA4WjCBiTEaMBgGCgmSJomT8ixk
AQEMCk1ENFA0UTg1WlExMzAxBgNVBAMMKmlQaG9uZSBEZXZlbG9wZXI6IGFtbW1p
IGFtbW1pIChXM1BSS1JDVDRRKTETMBEGA1UECwwKVktRNTZVQ0c4ODEUMBIGA1UE
CgwLYW1tbWkgYW1tbWkxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAwudboPuPnImOssBCw9vISRnnivreVwOuDAu77u47zIU8uTag
bzktX6pF54YToSLQHeOaNNQfZ7idccU2DKVBr3etz/++ca4HNadeUaEm2VWW4kEq
3iKIo1wZZhJJR6bQl4q797U0+f7eEXLKD4fjfidEF+ceAxAsX5YIuokq3K/B+XW3
tKk7D4nCaaCyJ9/+aJkFKT/oOxWRD0NYi5vXpni/3Plj5Qu3kDGrTUQaGCXXjRrA
E3mOVS4M2W5sFoOUpBxcfK7ajs+HUZNp0Gvb04OeD4O0lLTxcNu6omhG3MzOo81F
T+bkdxLM7XkIbNlIjYhyxGRynpgAKmiR9B/oeQIDAQABo4IB8TCCAe0wPwYIKwYB
BQUHAQEEMzAxMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5hcHBsZS5jb20vb2Nz
cDAzLXd3ZHIwMTAdBgNVHQ4EFgQUF8T1dPnBmZfKfG0+lHtczMuGy9owDAYDVR0T
AQH/BAIwADAfBgNVHSMEGDAWgBSIJxcJqbYYYIvs67r2R1nFUlSjtzCCAR0GA1Ud
IASCARQwggEQMIIBDAYJKoZIhvdjZAUBMIH+MIHDBggrBgEFBQcCAjCBtgyBs1Jl
bGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMg
YWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1z
IGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBj
ZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMDYGCCsGAQUFBwIBFipo
dHRwOi8vd3d3LmFwcGxlLmNvbS9jZXJ0aWZpY2F0ZWF1dGhvcml0eS8wDgYDVR0P
AQH/BAQDAgeAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMDMBMGCiqGSIb3Y2QGAQIB
Af8EAgUAMA0GCSqGSIb3DQEBCwUAA4IBAQA1//RUQ+hnCxfzSKO13qtuSb4IUrY5
bjkRKIAUlxN5aYVN5NIzCGxmahlDA/Rjw8MLVA8dWbT0QMSqx5IXC+Ov3JNZlkL0
5+RBuZEtZL7IZp0L3ZrCFtuizaunH9fZWbyFyfLACIYqZqP40N1+wIx1l4Es65Zu
WSeDeQMutda8DpmtCJhrnod9B1vfvDc3FUSmbJbvkLFh2UCgqtE9moLYI8qFMzqe
CQUJdPGdE+2WNv0wM8/cFIG/audSvEADKg1DgO+j6oP+urUe1gLsyzyv10J7/XA4
nmDuP1UNG7O7ADbdEOxhRiB96ZNwgcw9Q0wv9H9jMa+NNti6SxLud2+B
-----END CERTIFICATE----

By the way, I used online certificate decoder to decode dev.cer, it works well. Here is the url:

https://www.sslshopper.com/certificate-decoder.html

This site recommended to use openssl, but it failed.


问:
kubernetes dashboard: square/go-jose: error in cryptographic primitive
I am trying to make a CI/CD job on Gitlab that on commit will install a helm chart on a kubernetes cluster on google cloud. The only way i found how to do this was to copy the contents of the kube config file and paste it in a location inside my runner (that does not have the gcloud sdk), but then i realised that the token that gcloud would generate inside the config file would change periodically, so i looked for another solution and I found the application default credentials. I don't really understand the gcloud application-default set of commands tho, i ran login (on my local machine which has gcloud sdk) and it generated a json file with some credentials inside. Then i set the CLOUDSDK_CONTAINER_USE_APPLICATION_DEFAULT_CREDENTIALS env var to true and then I copied this file, and the re-generated config file inside the runner, and set the GOOGLE_APPLICATION_CREDENTIALS env to point to the file and it works. Im not quite sure why, tho.

What does gcloud application-default login actually do? I mean before doing this i didnt have the json file, and everytime i would run gcloud cluster get-credentials to switch between clusters i would see an access-token for each context that i could use to login on the dashboard, but after i did this on my local machine, sometimes the dashboard gives me a weird error: square/go-jose: error in cryptographic primitive.

Do you have any idea what im doing wrong?

答:
The error is due to a bad token (you switched your clusters contexts while logged in to the kubernetes dashboard)

If you sign out from the dashboard and sign in again, the error should disappear.


问:
Generate a PDF and return a response
Today I have faced a problem with generating PDF using KnpSnappyBundle on symfony.

I'm running a route using AJAX, the code works fine, but it does not generate the PDF,

What I want to accomplish here is to generate a PDF in new tab or window
and return a successful message to the client.

Here is my code:

```<code> /**
 * @Route("/api/release_bills/{month}/{year}/{region}", name="api_print_bills", methods={"GET","POST"})
 * @param BillRepository $billRepository
 * @param ConsumptionRepository $consumptionRepository
 * @param Request $request
 * @param Snappy $snappy
 * @param $month
 * @param $year
 * @param $region
 * @return Response
 * @throws Exception
 */
public function releaseBills(BillRepository $billRepository,ConsumptionRepository $consumptionRepository, Request $request, Snappy $snappy,  $month,$year,$region ): Response
{
    $error = array();
    $success = array();
    if( $month>0 && $month<13 || preg_match("/^\d{4}$/",$year)||$region!=''){

        if($year>=2018 && $year <=2050){
            $entityManager = $this->getDoctrine()->getManager();

                $bills = $consumptionRepository->findAllWaterMetersForBilling($month,$year,$region);

                $isBillsExisted = $billRepository->findAllBillsByDate($month,$year,$region);

                if(empty($bills)){
                    array_push($error,['error'=>'there is not bills to be release for this criteria : [ city: '.$region.', year :'.$year.', and Month : '.$month.'!]']);
                    return new JsonResponse($error);
                }

                $arr = array();
                $newBills = array();
                $billsEnd=end($bills);

                foreach ($bills as $key=>$b){
                    $wmNumber =  $b->getWaterMeter()->getWmNumber();
                    $fullName = $b->getWaterMeter()->getClient()->getFullName();
                    $cin = $b->getWaterMeter()->getClient()->getCin();
                    $address= $b->getWaterMeter()->getAddress();
                    $wmAddress = $b->getWaterMeter()->getAddress()->getStreetAddress();
                    $city = $b->getWaterMeter()->getAddress()->getCity();
                    $zipCode = $b->getWaterMeter()->getAddress()->getZipCode();
                    $billCode = $b->getId();
                    $consumptionDate = $b->getDate();
                    $oldConsumption=$b->getPreviousRecord();
                    $newConsumption=$b->getCurrentRecord();
                    $printDate =new \DateTime('now');
                    $consumption=$b->getConsumption();
                    $cost = $b->getCost()+10;
                    $wmReferenceNumber = $b->getWaterMeter()->getWmReferenceNumber();
                    $client= $b->getWaterMeter()->getClient();
                    // tranche calculation
                    //==================================================
                    $tranche1 = $consumption >= 5 ? 5 : $consumption; //4
                    $tranche2 = $consumption - $tranche1 >= 5 ? 5: 0; //0
                    $tranche3 = $consumption - $tranche1 - $tranche2;
                    //==================================================
                    $bill = new Bill();
                    $bill->setCode($wmNumber);
                    $bill->setFullName($fullName);
                    $bill->setCin($cin);
                    $bill->setPrintDate($printDate);
                    $bill->setCost($cost);
                    $bill->setConsumption($consumption);
                    $bill->setConsumptionDate($consumptionDate);
                    $bill->setPreviousRecord($oldConsumption);
                    $bill->setNewRecord($newConsumption);
                    $bill->setWaterMeter($b->getWaterMeter());
                    $bill->setRegion($city);
                    $bill->setClient($client);
                    $entityManager->persist($bill);
                    array_push($arr,['wmAddress'=>$wmAddress,'city'=>$city,'zipCode'=>$zipCode,'tranche1'=>$tranche1,'wmNumber'=>$wmNumber,'fullName'=>$fullName,'cin'=>$cin,'address'=>strval($address),'billCode'=>$billCode,'consumptionDate'=>$consumptionDate,'oldConsumption'=>$oldConsumption,'newConsumption'=>$newConsumption,'printDate'=>$printDate,'consumption'=>$consumption,'cost'=>$cost,'wmReferenceNumber'=>$wmReferenceNumber]);

                    if(count($arr)==6||$billCode==$billsEnd->getId()){
                        array_push($newBills,$arr);
                        $arr = array();
                    }

                }

                $date = new \DateTime('now');
                $html= $this->renderView('bill/bill.html.twig', array(
                    'arrayBills'=>$newBills,
                ));

                if($isBillsExisted){
                    return new PdfResponse(
                        $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                    );
                }
                $entityManager->flush(); //Persist objects that did not make up an entire batch
                $entityManager->clear();

                return new PdfResponse(
                    $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                );

            }
        }
    array_push($success,['success'=>'bills were successfully released']);
    return new JsonResponse($success);
}
</code>```

And my AJAX call is:

```<code> generatePDF = () =>{
        const {yearValue, monthValue, regionValue}= this.state;
        $.ajax({
            url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
            success: function (data) {
                console.log('DATA',data)
            }.bind(this)
        });
    };
</code>```

I believe that I can't return more than one response, anyway I have done console log to the response of the ajax call  displays the HTML content of the page I want to generate a PDF from and no PDF is being generated.

答:
try to modify Ajax like this:</p>

```<code>$.ajax({
  url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
  success: function(data) {
    var blob=new Blob([data]);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="<CHOOSE_FILENAME_WITH_EXTENSION>";
    link.click();
  }
});
</code>```

Title: Generate a PDF and return a response

Body:
Today I have faced a problem with generating PDF using KnpSnappyBundle on symfony.

I'm running a route using AJAX, the code works fine, but it does not generate the PDF,

What I want to accomplish here is to generate a PDF in new tab or window
and return a successful message to the client.

Here is my code:

 /**
 * @Route("/api/release_bills/{month}/{year}/{region}", name="api_print_bills", methods={"GET","POST"})
 * @param BillRepository $billRepository
 * @param ConsumptionRepository $consumptionRepository
 * @param Request $request
 * @param Snappy $snappy
 * @param $month
 * @param $year
 * @param $region
 * @return Response
 * @throws Exception
 */
public function releaseBills(BillRepository $billRepository,ConsumptionRepository $consumptionRepository, Request $request, Snappy $snappy,  $month,$year,$region ): Response
{
    $error = array();
    $success = array();
    if( $month>0 && $month<13 || preg_match("/^\d{4}$/",$year)||$region!=''){

        if($year>=2018 && $year <=2050){
            $entityManager = $this->getDoctrine()->getManager();

                $bills = $consumptionRepository->findAllWaterMetersForBilling($month,$year,$region);

                $isBillsExisted = $billRepository->findAllBillsByDate($month,$year,$region);

                if(empty($bills)){
                    array_push($error,['error'=>'there is not bills to be release for this criteria : [ city: '.$region.', year :'.$year.', and Month : '.$month.'!]']);
                    return new JsonResponse($error);
                }

                $arr = array();
                $newBills = array();
                $billsEnd=end($bills);

                foreach ($bills as $key=>$b){
                    $wmNumber =  $b->getWaterMeter()->getWmNumber();
                    $fullName = $b->getWaterMeter()->getClient()->getFullName();
                    $cin = $b->getWaterMeter()->getClient()->getCin();
                    $address= $b->getWaterMeter()->getAddress();
                    $wmAddress = $b->getWaterMeter()->getAddress()->getStreetAddress();
                    $city = $b->getWaterMeter()->getAddress()->getCity();
                    $zipCode = $b->getWaterMeter()->getAddress()->getZipCode();
                    $billCode = $b->getId();
                    $consumptionDate = $b->getDate();
                    $oldConsumption=$b->getPreviousRecord();
                    $newConsumption=$b->getCurrentRecord();
                    $printDate =new \DateTime('now');
                    $consumption=$b->getConsumption();
                    $cost = $b->getCost()+10;
                    $wmReferenceNumber = $b->getWaterMeter()->getWmReferenceNumber();
                    $client= $b->getWaterMeter()->getClient();
                    // tranche calculation
                    //==================================================
                    $tranche1 = $consumption >= 5 ? 5 : $consumption; //4
                    $tranche2 = $consumption - $tranche1 >= 5 ? 5: 0; //0
                    $tranche3 = $consumption - $tranche1 - $tranche2;
                    //==================================================
                    $bill = new Bill();
                    $bill->setCode($wmNumber);
                    $bill->setFullName($fullName);
                    $bill->setCin($cin);
                    $bill->setPrintDate($printDate);
                    $bill->setCost($cost);
                    $bill->setConsumption($consumption);
                    $bill->setConsumptionDate($consumptionDate);
                    $bill->setPreviousRecord($oldConsumption);
                    $bill->setNewRecord($newConsumption);
                    $bill->setWaterMeter($b->getWaterMeter());
                    $bill->setRegion($city);
                    $bill->setClient($client);
                    $entityManager->persist($bill);
                    array_push($arr,['wmAddress'=>$wmAddress,'city'=>$city,'zipCode'=>$zipCode,'tranche1'=>$tranche1,'wmNumber'=>$wmNumber,'fullName'=>$fullName,'cin'=>$cin,'address'=>strval($address),'billCode'=>$billCode,'consumptionDate'=>$consumptionDate,'oldConsumption'=>$oldConsumption,'newConsumption'=>$newConsumption,'printDate'=>$printDate,'consumption'=>$consumption,'cost'=>$cost,'wmReferenceNumber'=>$wmReferenceNumber]);

                    if(count($arr)==6||$billCode==$billsEnd->getId()){
                        array_push($newBills,$arr);
                        $arr = array();
                    }

                }

                $date = new \DateTime('now');
                $html= $this->renderView('bill/bill.html.twig', array(
                    'arrayBills'=>$newBills,
                ));

                if($isBillsExisted){
                    return new PdfResponse(
                        $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                    );
                }
                $entityManager->flush(); //Persist objects that did not make up an entire batch
                $entityManager->clear();

                return new PdfResponse(
                    $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                );

            }
        }
    array_push($success,['success'=>'bills were successfully released']);
    return new JsonResponse($success);
}

And my AJAX call is:

 generatePDF = () =>{
        const {yearValue, monthValue, regionValue}= this.state;
        $.ajax({
            url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
            success: function (data) {
                console.log('DATA',data)
            }.bind(this)
        });
    };

I believe that I can't return more than one response, anyway I have done console log to the response of the ajax call  displays the HTML content of the page I want to generate a PDF from and no PDF is being generated.

Body:
try to modify Ajax like this:

$.ajax({
  url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
  success: function(data) {
    var blob=new Blob([data]);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="<CHOOSE_FILENAME_WITH_EXTENSION>";
    link.click();
  }
});