问:
Different cells CollectionView rxswift
Good evening.
Tell me please
I need to make such an implementation
Have: CollectionView
Rxswift
The maximum number of cells is 6
If there are less than 6 elements in a certain array, then the first cells are filled with one type (by the number of elements in the array), and the rest with other cells.</p>

```<code>collectionView.register(UINib(nibName: "PhotoCollectionCell", bundle: nil), forCellWithReuseIdentifier: "PhotoCell")
collectionView.register(UINib(nibName: "EmptyCollectionCell", bundle: nil), forCellWithReuseIdentifier: "EmptyCell")
</code>```

答:
You need to import RxDataSources in case you want different cell type.</p>

```<code>        // TableView Cell Nib Register
        tableView.register(R.nib.meChatCell)
        tableView.register(R.nib.otherChatCell)

        vm.output.chats
        .bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

            if item.userId == 0 {
                let cellIdentifier = R.reuseIdentifier.meChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! MeChatCell
                cell.vm = item
                return cell
            } else {
                let cellIdentifier = R.reuseIdentifier.otherChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! OtherChatCell
                cell.vm = item
                return cell
            }

        }.disposed(by: disposeBag)
}
</code>```

Title: Different cells CollectionView rxswift

Body:
Good evening.
Tell me please
I need to make such an implementation
Have: CollectionView
Rxswift
The maximum number of cells is 6
If there are less than 6 elements in a certain array, then the first cells are filled with one type (by the number of elements in the array), and the rest with other cells.

collectionView.register(UINib(nibName: "PhotoCollectionCell", bundle: nil), forCellWithReuseIdentifier: "PhotoCell")
collectionView.register(UINib(nibName: "EmptyCollectionCell", bundle: nil), forCellWithReuseIdentifier: "EmptyCell")

Body:
You need to import RxDataSources in case you want different cell type.

        // TableView Cell Nib Register
        tableView.register(R.nib.meChatCell)
        tableView.register(R.nib.otherChatCell)

        vm.output.chats
        .bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

            if item.userId == 0 {
                let cellIdentifier = R.reuseIdentifier.meChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! MeChatCell
                cell.vm = item
                return cell
            } else {
                let cellIdentifier = R.reuseIdentifier.otherChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! OtherChatCell
                cell.vm = item
                return cell
            }

        }.disposed(by: disposeBag)
}


来源: stackexchange

问:
Text widget must not be null
I pass argument through a pushNamedandRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

```<code>CustomButton(
                    buttonText: 'Go',
                    buttonClick: () {Navigator.pushNamedAndRemoveUntil(context, Next.id, (route) => false, arguments: "123456789");},
                  ),

class Next extends StatefulWidget {

  const Next({this.number});
  static const id = "next";
  final String number;
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
 @override
  Widget build(BuildContext context) {
       return Scaffold(
body: Container(child: Center(child: Text(widget.number)))
)
}
}
</code>```

Error is
Failed assertion: line 298 pos 10: 'data != null'

答:
its because your passed parameter is null

and if you want to handle the error you should use Text widget like this :

```<code>Text(widget.number ?? '')
</code>```

and you should pass parameter like this

```<code>CustomButton(
  buttonText: 'Go',
  buttonClick: () {
      navigator.pushAndRemoveUntil(
         MaterialPageRoute(builder: (BuildContext context) => Next(id: '123456789')),
        (Route<dynamic> route) => false,
      );
),
</code>```

ContentLicense: CC BY-SA 4.0

Title: Text widget must not be null

Body:
I pass argument through a pushNamedandRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

CustomButton(
                    buttonText: 'Go',
                    buttonClick: () {Navigator.pushNamedAndRemoveUntil(context, Next.id, (route) => false, arguments: "123456789");},
                  ),

class Next extends StatefulWidget {

  const Next({this.number});
  static const id = "next";
  final String number;
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
 @override
  Widget build(BuildContext context) {
       return Scaffold(
body: Container(child: Center(child: Text(widget.number)))
)
}
}

Error is
Failed assertion: line 298 pos 10: 'data != null'

Body:
its because your passed parameter is null

and if you want to handle the error you should use Text widget like this :

Text(widget.number ?? '')

and you should pass parameter like this

CustomButton(
  buttonText: 'Go',
  buttonClick: () {
      navigator.pushAndRemoveUntil(
         MaterialPageRoute(builder: (BuildContext context) => Next(id: '123456789')),
        (Route<dynamic> route) => false,
      );
),


问:
Continue statement in Pl/sql
I am working Oracle 10g. I am running this pl/sql  block

```<code>Declare
cursor Get_Data is select * from employee for update;
data Get_Data%rowtype;

Begin

for data in Get_Data loop
  if(data.salary=5000) then
  continue;
  else
   update employee set salary= salary+3000 where current of Get_Data;
  end if;
end loop;
end;
</code>```

It is giving me this Error  : identifier 'CONTINUE' must be declared

please suggest me how to resolve this problem.

答:
Try</p>

```<code>Declare
    cursor Get_Data is select * from employee for update;
    data Get_Data%rowtype;

    Begin

    for data in Get_Data loop
      if(data.salary<>5000)
           update employee set salary= salary+3000 where current of Get_Data;
      end if;
    end loop;
    end;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Continue statement in Pl/sql

Body:
I am working Oracle 10g. I am running this pl/sql  block

Declare
cursor Get_Data is select * from employee for update;
data Get_Data%rowtype;

Begin

for data in Get_Data loop
  if(data.salary=5000) then
  continue;
  else
   update employee set salary= salary+3000 where current of Get_Data;
  end if;
end loop;
end;

It is giving me this Error  : identifier 'CONTINUE' must be declared

please suggest me how to resolve this problem.

Body:
Try

Declare
    cursor Get_Data is select * from employee for update;
    data Get_Data%rowtype;

    Begin

    for data in Get_Data loop
      if(data.salary<>5000)
           update employee set salary= salary+3000 where current of Get_Data;
      end if;
    end loop;
    end;


问:
Accessing multiple allure reports over http
I have test-results in a folder, which will be updated with new executions on every test run.

```<code>[root@server test-results]# ls -lrt /var/log/test-results/
total 352
drwxrwxrwx. 14 root root 4096 Jan 10 10:28 9ca9cd74-21d3-4d39-b556-1ca914a37408
drwxrwxrwx. 14 root root 4096 Jan 10 10:41 4fc5f9fa-ee03-4370-98bc-0cca6dcb95d6
drwxrwxrwx. 14 root root 4096 Jan 10 13:00 9e7a9239-cbd4-48a1-929e-bf90892903b0
drwxrwxrwx. 14 root root 4096 Jan 11 09:09 544bd6c9-8d43-4e17-bbc7-8395498e98b6
drwxr-xr-x. 14 root root 4096 Jan 14 10:40 faa3284c-01b0-4581-89fd-57a1919d13b7
drwxr-xr-x. 14 root root 4096 Jan 14 11:31 ee84c6f4-048d-4e9d-96c0-2bc4f6ab3f53
drwxr-xr-x. 14 root root 4096 Jan 14 11:46 c229cacb-1e27-4629-a67f-3eb2965006f9
drwxr-xr-x. 14 root root 4096 Jan 14 12:35 2cca5070-0333-4d95-a1e5-c409c3185bf3
drwxr-xr-x. 14 root root 4096 Jan 14 13:13 e19c3bd1-3a1f-459a-b8f2-5e1bfad11fe9
</code>```

Each of this folder has test-data which can be parsed by the allure engine.

I am trying to find a way to view these results in the following way.

```<code>https://localhost:port/<test folder name/
https://localhost:port/9ca9cd74-21d3-4d39-b556-1ca914a37408/
https://localhost:port/4fc5f9fa-ee03-4370-98bc-0cca6dcb95d6/
https://localhost:port/9e7a9239-cbd4-48a1-929e-bf90892903b0/
https://localhost:port/544bd6c9-8d43-4e17-bbc7-8395498e98b6/
</code>```

I tried using https://github.com/fescobar/allure-docker-service. This does provide a way to view the allure report. But, it cannot individually allow me to have separate links for different test-results. Instead, it can show allure report of data in only one folder.

I am not sure of the right way to do it. Please let me know if any information is needed.

答:
Now you can handle multiple projects with Allure Docker Service
https://github.com/fescobar/allure-docker-service#MULTIPLE-PROJECTS---REMOTE-REPORTS</p>

Body:
I have test-results in a folder, which will be updated with new executions on every test run.

[root@server test-results]# ls -lrt /var/log/test-results/
total 352
drwxrwxrwx. 14 root root 4096 Jan 10 10:28 9ca9cd74-21d3-4d39-b556-1ca914a37408
drwxrwxrwx. 14 root root 4096 Jan 10 10:41 4fc5f9fa-ee03-4370-98bc-0cca6dcb95d6
drwxrwxrwx. 14 root root 4096 Jan 10 13:00 9e7a9239-cbd4-48a1-929e-bf90892903b0
drwxrwxrwx. 14 root root 4096 Jan 11 09:09 544bd6c9-8d43-4e17-bbc7-8395498e98b6
drwxr-xr-x. 14 root root 4096 Jan 14 10:40 faa3284c-01b0-4581-89fd-57a1919d13b7
drwxr-xr-x. 14 root root 4096 Jan 14 11:31 ee84c6f4-048d-4e9d-96c0-2bc4f6ab3f53
drwxr-xr-x. 14 root root 4096 Jan 14 11:46 c229cacb-1e27-4629-a67f-3eb2965006f9
drwxr-xr-x. 14 root root 4096 Jan 14 12:35 2cca5070-0333-4d95-a1e5-c409c3185bf3
drwxr-xr-x. 14 root root 4096 Jan 14 13:13 e19c3bd1-3a1f-459a-b8f2-5e1bfad11fe9

Each of this folder has test-data which can be parsed by the allure engine.

I am trying to find a way to view these results in the following way.

https://localhost:port/<test folder name/
https://localhost:port/9ca9cd74-21d3-4d39-b556-1ca914a37408/
https://localhost:port/4fc5f9fa-ee03-4370-98bc-0cca6dcb95d6/
https://localhost:port/9e7a9239-cbd4-48a1-929e-bf90892903b0/
https://localhost:port/544bd6c9-8d43-4e17-bbc7-8395498e98b6/

I tried using https://github.com/fescobar/allure-docker-service. This does provide a way to view the allure report. But, it cannot individually allow me to have separate links for different test-results. Instead, it can show allure report of data in only one folder.

I am not sure of the right way to do it. Please let me know if any information is needed.


问:
Apache + PHP: how to change the value of $_SERVER['SERVER_NAME'] in apache?
for example, i have mysite.com and beta.mysite.com. both point to the same index file using the virtualHost directive. what will i do in the apache conf so that when i access the $_SERVER['SERVER_NAME'], the value would still be mysite.com?

this should be flexible that only the beta would be removed.

答:
Maybe you could use a ServerAlias in your VirtualHost directive, and use only one VirtualHost directive:</p>

```<code><VirtualHost *:80>
  ServerName mysite.com
  ServerAlias beta.mysite.com
  ...
</VirtualHost>
</code>```

Body:
Maybe you could use a ServerAlias in your VirtualHost directive, and use only one VirtualHost directive:

<VirtualHost *:80>
  ServerName mysite.com
  ServerAlias beta.mysite.com
  ...
</VirtualHost>


问:
Xamarin Android Opening PDF file
I use the Xamarin.Forms 4.6.0.800

I view a PDF file on Android using the following code in the constructor of my ContentPage.

```<code>        // Get access to the local file system
        var localFileService = DependencyService.Get<ILocalFileService>();

        // Save the PDF to a temporary file
        var temporaryFile = localFileService.SaveToTempPDFFile(reportName, pdfData);

        // Set the WebView to reference the temporary PDF file
        PdfView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={temporaryFile}";
</code>```

The XAML is simply:

```<code><ContentPage.Content>
    <WebView
        x:Name="PdfView"
        VerticalOptions="Fill"
        HorizontalOptions="Fill" />
</ContentPage.Content>
</code>```

This has been working for quite a while, but today on re-testing, I get the following error:

```<code>file:///Android_asset/pdfjs/web/viewer.html?file=/data/user/0/com.myApp/cache/reportname.pdf could not be loaded because:

net::ERR_FILE_NOT_FOUND
</code>```

Has something changed in Xamarin recently to cause this?  In the meantime I am searching for something I may have changed that could be causing this error (as it has been working fine for quite a while now).

答:
I found what was causing it, but no idea why.  In the Android project, I had set the Platform Target to x64.  Changed it back to Any CPU and it all works again???

It has reappeared again, but only when I install it on a Pixel 4 (my test phone).  Emulators are OK.

Title: Xamarin Android Opening PDF file

Body:
I use the Xamarin.Forms 4.6.0.800

I view a PDF file on Android using the following code in the constructor of my ContentPage.

        // Get access to the local file system
        var localFileService = DependencyService.Get<ILocalFileService>();

        // Save the PDF to a temporary file
        var temporaryFile = localFileService.SaveToTempPDFFile(reportName, pdfData);

        // Set the WebView to reference the temporary PDF file
        PdfView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={temporaryFile}";

The XAML is simply:

<ContentPage.Content>
    <WebView
        x:Name="PdfView"
        VerticalOptions="Fill"
        HorizontalOptions="Fill" />
</ContentPage.Content>

This has been working for quite a while, but today on re-testing, I get the following error:

file:///Android_asset/pdfjs/web/viewer.html?file=/data/user/0/com.myApp/cache/reportname.pdf could not be loaded because:

net::ERR_FILE_NOT_FOUND

Has something changed in Xamarin recently to cause this?  In the meantime I am searching for something I may have changed that could be causing this error (as it has been working fine for quite a while now).


问:
Control flow statements. How many years should pass until goal money
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}
</code>```

Test input: 100 15 120

Correct output: 2

Your code output: 1

答:
```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Stackoverflow_053120
{
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        System.out.println("Enter money, percent and goal");
        String input[] = in.readLine().split(" ");
        int money = Integer.parseInt(input[0]);
        int percent = Integer.parseInt(input[1]);
        int goal = Integer.parseInt(input[2]);

        int years = 0;
        while(money < goal)
        {
            money = (money * (100+percent)) / 100;
            years++;
        }
        System.out.println(years);
    }
}
</code>```

Body:
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}

Test input: 100 15 120

Correct output: 2

Your code output: 1


问:
how to save canvas as png image?
I have a canvas element with a drawing in it, and I want to create a button that when clicked on, it will save the image as a png file. So it should open up the save, open, close dialog box...

I do it using this code

```<code>var canvas = document.getElementById("myCanvas");
window.open(canvas.toDataURL("image/png"));
</code>```

But when I test it out in IE9, a new window opens up saying "the web page cannot be displayed"
and the url of it is:

```<code>data:image/png;base64,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
</code>```

Anyone know how to fix this?

答:
I really like Tovask's answer but it doesn't work due to the function having the name download (this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".

The following code has been tested in Chrome and Firefox and seems to work fine in both.

JavaScript:

```<code>function prepDownload(a, canvas, name) {
    a.download = name
    a.href = canvas.toDataURL()
}
</code>```

HTML:

```<code><a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>
</code>```

Title: how to save canvas as png image?

Body:
I have a canvas element with a drawing in it, and I want to create a button that when clicked on, it will save the image as a png file. So it should open up the save, open, close dialog box...

I do it using this code

var canvas = document.getElementById("myCanvas");
window.open(canvas.toDataURL("image/png"));

But when I test it out in IE9, a new window opens up saying "the web page cannot be displayed"
and the url of it is:

data:image/png;base64,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

Anyone know how to fix this?

Body:
I really like Tovask's answer but it doesn't work due to the function having the name download (this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".

The following code has been tested in Chrome and Firefox and seems to work fine in both.

JavaScript:

function prepDownload(a, canvas, name) {
    a.download = name
    a.href = canvas.toDataURL()
}

HTML:

<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>


问:
Isolate substring
Given the following string:

```<code>24^5915^7569^10070-3
</code>```

How do I isolate the "10070" from it? In theory, I'd get the last item from the caret-delimited list, then split that. Can do it in ColdFusion but not jQuery. I need to note that the list/array can vary in length, i.e. there could be more or fewer caret delimiters, but the "-" delimiter will only ever be one, at the very end.

答:
A one-liner:

console.log("24^5915^7569^10070-3".split("^").pop().split("-").shift());```

If you can figure out a proper regular expression that suits your needs, you can also solve it (probably in a more elegant way) using String.prototype.match().

Title: Isolate substring

Body:
Given the following string:

24^5915^7569^10070-3

How do I isolate the "10070" from it? In theory, I'd get the last item from the caret-delimited list, then split that. Can do it in ColdFusion but not jQuery. I need to note that the list/array can vary in length, i.e. there could be more or fewer caret delimiters, but the "-" delimiter will only ever be one, at the very end.

Body:
A one-liner:

console.log("24^5915^7569^10070-3".split("^").pop().split("-").shift());

If you can figure out a proper regular expression that suits your needs, you can also solve it (probably in a more elegant way) using String.prototype.match().


问:
Signalr with angular and .net core error with code 1006
I am facing problem with the signalr when hosting angular application on the IIS it keeps showing the following error on the console:

[2020-05-31T08:09:00.838Z] Error: Connection disconnected with error 'Error: WebSocket closed with status code: 1006 ().'.
```

<p>keeping in mind that once I have hosted the angular application using nodeJs it works fine, yet I need to host the angular application on IIS.</p>

<p>I am using "@microsoft/signalr" and aspcore 3.1 </p>

<p>My code sample angular:</p>

<pre class="lang-sh prettyprint-override"><code>  constructor(private fb: FormBuilder, private router: Router) {
    //establish a new connection on the logging user group
    this.signalRConnection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Information)
      .withUrl(this.hubUrl)
      .build();
    this.signalRConnection.start().then(() => {
      this.session.id = this.signalRConnection.connectionId;
      this.signalRConnection.send("RegisterOnlineUser", this.session, 'title', 'url');
      this.signalRConnection.send("GetOnlineUsers");
    });
  }
</code>```

aspcore :

        public async void registerOnlineUser(SessionInfo session)
        {

            await Groups.AddToGroupAsync(Context.ConnectionId, session.group);

          await Clients.Group(Users).SendAsync("RegisterOnlineUser", session);

            }

```

答:
You have to enable websocket in IIS settings.
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/websocket</p>

Body:
I am facing problem with the signalr when hosting angular application on the IIS it keeps showing the following error on the console:

[2020-05-31T08:09:00.838Z] Error: Connection disconnected with error 'Error: WebSocket closed with status code: 1006 ().'.

keeping in mind that once I have hosted the angular application using nodeJs it works fine, yet I need to host the angular application on IIS.

I am using "@microsoft/signalr" and aspcore 3.1

My code sample angular:

  constructor(private fb: FormBuilder, private router: Router) {
    //establish a new connection on the logging user group
    this.signalRConnection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Information)
      .withUrl(this.hubUrl)
      .build();
    this.signalRConnection.start().then(() => {
      this.session.id = this.signalRConnection.connectionId;
      this.signalRConnection.send("RegisterOnlineUser", this.session, 'title', 'url');
      this.signalRConnection.send("GetOnlineUsers");
    });
  }

aspcore :

        public async void registerOnlineUser(SessionInfo session)
        {

            await Groups.AddToGroupAsync(Context.ConnectionId, session.group);

          await Clients.Group(Users).SendAsync("RegisterOnlineUser", session);

            }


问:
Can we delete the .ova file after importing it in VirtualBox?
I installed VirtualBox on my MacBook and downloaded the Kali Linux .ova file to use as a virtual machine. However, I am running out of storage and the .ova file is taking up almost 4 GB of storage. Can I delete the .ova file now that I have imported it in VirtualBox?</p>

答: Yes. You can delete the .ova file from your OS if you're sure the VM imported successfully


问:
how to set cluster dns to using coredns
I am deployed coredns in kubernetes cluster, but the mysql pod(ip:10.244.8.43) in the slave node is not using coredns ip as name server, I login to mysql pods and find the nameserver:

```<code>root@apollo-mysql-85fd475fc9-sjfhg:/# cat /etc/resolv.conf
nameserver 10.96.0.10
search sre.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
</code>```

but the coredns (v1.6.7) pod's ip is: 10.244.6.34, where is the problem? what should I do to make coredns work to my cluster pods? and this is my pod define :

```<code>kind: Deployment
apiVersion: apps/v1
metadata:
  name: apollo-mysql
  namespace: sre
  selfLink: /apis/apps/v1/namespaces/sre/deployments/apollo-mysql
  uid: b7a2f852-894d-4686-816c-21737535dbea
  resourceVersion: '498210'
  generation: 42
  creationTimestamp: '2020-05-30T11:27:09Z'
  annotations:
    deployment.kubernetes.io/revision: '4'
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"apollo-mysql","namespace":"sre"},"spec":{"selector":{"matchLabels":{"app":"apollo-mysql"}},"strategy":{"type":"Recreate"},"template":{"metadata":{"labels":{"app":"apollo-mysql"}},"spec":{"containers":[{"env":[{"name":"MYSQL_ROOT_PASSWORD","value":"gl4LucnXwLeLwAd29QqJn4"}],"image":"mysql:5.7","name":"mysql","ports":[{"containerPort":3306,"name":"mysql"}],"volumeMounts":[{"mountPath":"/var/lib/mysql","name":"apollo-mysql-persistent-storage"}]}],"volumes":[{"name":"apollo-mysql-persistent-storage","persistentVolumeClaim":{"claimName":"apollo-mysql-pv-claim"}}]}}}}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: apollo-mysql
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: apollo-mysql
    spec:
      volumes:
        - name: apollo-mysql-persistent-storage
          persistentVolumeClaim:
            claimName: apollo-mysql-pv-claim
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gl4LucnXwLeLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler
  strategy:
    type: Recreate
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600
status:
  observedGeneration: 42
  replicas: 1
  updatedReplicas: 1
  readyReplicas: 1
  availableReplicas: 1
  conditions:
    - type: Progressing
      status: 'True'
      lastUpdateTime: '2020-05-31T03:34:11Z'
      lastTransitionTime: '2020-05-30T11:38:19Z'
      reason: NewReplicaSetAvailable
      message: ReplicaSet "apollo-mysql-5f5c49c448" has successfully progressed.
    - type: Available
      status: 'True'
      lastUpdateTime: '2020-05-31T08:34:56Z'
      lastTransitionTime: '2020-05-31T08:34:56Z'
      reason: MinimumReplicasAvailable
      message: Deployment has minimum availability.
</code>```

答:
10.96.0.10 is commonly used as the IP for the kube-dns service which is provided by the coredns pods.

```<code>$ kubectl describe svc kube-dns -n kube-system
Name:              kube-dns
...
Type:              ClusterIP
IP:                10.96.0.10
Port:              dns  53/UDP
TargetPort:        53/UDP
Endpoints:         192.168.150.144:53,192.168.24.204:53
...
</code>```

So I think your coredns is being used. Check the IPs on the core-dns pods to be sure that the IPs line up:

```<code>$ kubectl describe pod -n kube-system coredns-....-.... | grep IP
IP:                   192.168.150.144
</code>```

Notice in my case the 192.168.150.144 is the pod IP of a coredns pod and it is listed in the service endpoints.

Title: how to set cluster dns to using coredns

Body:
I am deployed coredns in kubernetes cluster, but the mysql pod(ip:10.244.8.43) in the slave node is not using coredns ip as name server, I login to mysql pods and find the nameserver:

root@apollo-mysql-85fd475fc9-sjfhg:/# cat /etc/resolv.conf
nameserver 10.96.0.10
search sre.svc.cluster.local svc.cluster.local cluster.local
options ndots:5

but the coredns (v1.6.7) pod's ip is: 10.244.6.34, where is the problem? what should I do to make coredns work to my cluster pods? and this is my pod define :

kind: Deployment
apiVersion: apps/v1
metadata:
  name: apollo-mysql
  namespace: sre
  selfLink: /apis/apps/v1/namespaces/sre/deployments/apollo-mysql
  uid: b7a2f852-894d-4686-816c-21737535dbea
  resourceVersion: '498210'
  generation: 42
  creationTimestamp: '2020-05-30T11:27:09Z'
  annotations:
    deployment.kubernetes.io/revision: '4'
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"apollo-mysql","namespace":"sre"},"spec":{"selector":{"matchLabels":{"app":"apollo-mysql"}},"strategy":{"type":"Recreate"},"template":{"metadata":{"labels":{"app":"apollo-mysql"}},"spec":{"containers":[{"env":[{"name":"MYSQL_ROOT_PASSWORD","value":"gl4LucnXwLeLwAd29QqJn4"}],"image":"mysql:5.7","name":"mysql","ports":[{"containerPort":3306,"name":"mysql"}],"volumeMounts":[{"mountPath":"/var/lib/mysql","name":"apollo-mysql-persistent-storage"}]}],"volumes":[{"name":"apollo-mysql-persistent-storage","persistentVolumeClaim":{"claimName":"apollo-mysql-pv-claim"}}]}}}}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: apollo-mysql
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: apollo-mysql
    spec:
      volumes:
        - name: apollo-mysql-persistent-storage
          persistentVolumeClaim:
            claimName: apollo-mysql-pv-claim
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gl4LucnXwLeLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler
  strategy:
    type: Recreate
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600
status:
  observedGeneration: 42
  replicas: 1
  updatedReplicas: 1
  readyReplicas: 1
  availableReplicas: 1
  conditions:
    - type: Progressing
      status: 'True'
      lastUpdateTime: '2020-05-31T03:34:11Z'
      lastTransitionTime: '2020-05-30T11:38:19Z'
      reason: NewReplicaSetAvailable
      message: ReplicaSet "apollo-mysql-5f5c49c448" has successfully progressed.
    - type: Available
      status: 'True'
      lastUpdateTime: '2020-05-31T08:34:56Z'
      lastTransitionTime: '2020-05-31T08:34:56Z'
      reason: MinimumReplicasAvailable
      message: Deployment has minimum availability.

Body:
10.96.0.10 is commonly used as the IP for the kube-dns service which is provided by the coredns pods.

$ kubectl describe svc kube-dns -n kube-system
Name:              kube-dns
...
Type:              ClusterIP
IP:                10.96.0.10
Port:              dns  53/UDP
TargetPort:        53/UDP
Endpoints:         192.168.150.144:53,192.168.24.204:53
...

So I think your coredns is being used. Check the IPs on the core-dns pods to be sure that the IPs line up:

$ kubectl describe pod -n kube-system coredns-....-.... | grep IP
IP:                   192.168.150.144

Notice in my case the 192.168.150.144 is the pod IP of a coredns pod and it is listed in the service endpoints.


问:
How can RxJava interval/infinite counter be implemented with Kotlin Flow in reactive way?
How can interval counterpart of RxJava interval, infinite counter with delay and time unit, implemented with Flow in reactive way? And how should cancel mechanism work since only way to cancel a Flow is to cancel scope or job of the coroutine and after that coroutine is canceled it does not work?</p>

答:
I made a simple implementation of RxJava interval.

```<code>fun interval(timeInMillis: Long, timeUnit: TimeUnit): Flow<Long> = flow {

    var counter: Long = 0

    val delayTime = when (timeUnit) {
        TimeUnit.MICROSECONDS -> timeInMillis / 1000
        TimeUnit.NANOSECONDS -> timeInMillis / 1_000_000
        TimeUnit.SECONDS -> timeInMillis * 1000
        TimeUnit.MINUTES -> 60 * timeInMillis * 1000
        TimeUnit.HOURS -> 60 * 60 * timeInMillis * 1000
        TimeUnit.DAYS -> 24 * 60 * 60 * timeInMillis * 1000
        else -> timeInMillis
    }

    while (true) {
        delay(delayTime)
        emit(counter++)
    }

}
</code>```

And used it  with launchIn to have job similar to disposable.

```<code>val coroutineScope = CoroutineScope(SupervisorJob())

  val job =  coroutineScope.launch {
        val job = interval(1, TimeUnit.SECONDS)
            .onStart {
                emit(-1)
            }
            .onEach {
                println(it)
            }
            .map {
                "Current time $it"
            }
            .launchIn(coroutineScope)

    }
</code>```

Used another coroutineScope to not cancel other jobs that are in existing coroutineScope, when a coroutineScope.cancel() or cancel function of job belong to that coroutineScope is canceled jobs cannot be started again.

Of course this answer might be improved or better one, i don't accept it.

Body:
I made a simple implementation of RxJava interval.

fun interval(timeInMillis: Long, timeUnit: TimeUnit): Flow<Long> = flow {

    var counter: Long = 0

    val delayTime = when (timeUnit) {
        TimeUnit.MICROSECONDS -> timeInMillis / 1000
        TimeUnit.NANOSECONDS -> timeInMillis / 1_000_000
        TimeUnit.SECONDS -> timeInMillis * 1000
        TimeUnit.MINUTES -> 60 * timeInMillis * 1000
        TimeUnit.HOURS -> 60 * 60 * timeInMillis * 1000
        TimeUnit.DAYS -> 24 * 60 * 60 * timeInMillis * 1000
        else -> timeInMillis
    }

    while (true) {
        delay(delayTime)
        emit(counter++)
    }

}

And used it  with launchIn to have job similar to disposable.

val coroutineScope = CoroutineScope(SupervisorJob())

  val job =  coroutineScope.launch {
        val job = interval(1, TimeUnit.SECONDS)
            .onStart {
                emit(-1)
            }
            .onEach {
                println(it)
            }
            .map {
                "Current time $it"
            }
            .launchIn(coroutineScope)

    }

Used another coroutineScope to not cancel other jobs that are in existing coroutineScope, when a coroutineScope.cancel() or cancel function of job belong to that coroutineScope is canceled jobs cannot be started again.

Of course this answer might be improved or better one, i don't accept it.


答:
You could user pattern matching with a regex:

console.log("24^5915^7569^10070-3".match("[\^][0-9]+[-]")[0].slice(1, -1));```

It takes the pattern ^numbers- the removes ^ and - from the first match.

Title: Isolate substring

Body:
You could user pattern matching with a regex:

console.log("24^5915^7569^10070-3".match("[\^][0-9]+[-]")[0].slice(1, -1));

It takes the pattern ^numbers- the removes ^ and - from the first match.


问:
Is there a way to run the discord SDK code for C# in python?
Im trying to use the discord SDK on my python app and the only non-unity and non-unreal way to do this is with C#

I have absolutely no idea how to code in C# but Discord says all i need is one line of code

I have tried converting my app to C# but some of the libraries on python isnt supported on C#

I also cant find any python wrappers for discord so i need a way to run the code from python

EDIT:

I have deciced to take the time to learn C# instead of looking for a quick patch like i usually do

答:
Generally, trying to use one language's SDK from another usually isn't trivial.  Your best bet to use it directly from Python is probably IronPython, which allows you to call .NET APIs from Python.

If you're willing to use an unofficial API wrapper (I'm not sure if there's something special about the C# SDK), discord.py exists as a solution.  That would hopefully avoid the need to use the C# SDK specifically.  Docs for that are here.


问:
Optimize Server Side Blazor application
I've try to improve performance of a server side blazor application and got a result from Google Chrome Lighthouse, which shows very much work in parsing / Script Evaluation.

Has someone experience if this is normal in with server blazor or how to improve this thing in production mode?

Just want to know some hints or experiences which part of application could cause this behaviour.

Thanks!

答:
Also, make sure you have prerendering on.

Then, see what scripts you can shave off, especially jQuery widgets. Load scripts on demand when you will be initializing then only.

Title: Optimize Server Side Blazor application


问:
Very slow download from GitHub
When cloning a repository from GitHub I sometimes only get a download rate between 50-100 KiB/sec (staying stable) while most of the time I have about 10 MiB/sec. When cloning the same repository from a different machine (= different global IP) I get full speed.

Does GitHub impose a rate limit on repository cloning? The repository in question is quite big (~100 MiB) and I clone it about twice a day.

答: Try gitclone.com and use --depth = 1 at the same time. See gitcache for the implementation</p>

Title: Very slow download from GitHub


问:
JavaScript - Loop between two dates. Start and end date
I'm trying to console.log all the dates between two dates.

Here is the code i have so far:

```<code>    var dString = "18.04.2018";
    var dParts = dString.split('.');
    var in30Days = new Date(dParts[2] + '/' +
                            dParts[1] + '/' +
                            (+dParts[0] + 10)
                   );
    var endDate =  in30Days.getDate() + "." + (in30Days.getMonth()+1) + "." +in30Days.getFullYear();
    console.log("Now:" + dString + " EndDate: " + endDate);

    for (var d = dString; d <= endDate; d.setDate(d.getDate() + 1)) {
        var loopDay = new Date(d);
        console.log("Day:" + loopDay);
    }
</code>```

The end date is the start date plus 10 days.

Here is the console log output i receive:

```<code>Now:18.04.2018 EndDate: 28.4.2018
Day:Invalid Date
</code>```

Why the date is invalid. Where is my mistake ?

答:
 $('#button').on('click',function(){
    var end = $('#end').val()
    var start = $('#start').val()
    var tableau = testdiff(new Date(start),new Date(end));
    console.log(tableau);
  })

  function testdiff(from,to){
    var resultat=[];
    while (from <= to) {
        var dd = from.getDate();
        var mm = from.getMonth()+1;
        var yyyy = from.getFullYear();
        if(dd<10) {dd='0'+dd;}
        if(mm<10){mm='0'+mm;}
        var vDate = yyyy+'-'+mm+'-'+dd;
        resultat.push(vDate);
        from = new Date(from.setDate(from.getDate() + 1));
    }
    return resultat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="my-2 mx-2">
        <div class="col-sm-4">
            <label for="">start</label>
            <input type="date" name="start" id="start" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4">
            <label for=""> end</label>
            <input type="date" name="end" id="end" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4 my-3">
            <button type="button" id="button" class="btn btn-default">clic</button>
        </div>

    </div></code>```

use jquery

Body:
I'm trying to console.log all the dates between two dates.

Here is the code i have so far:

    var dString = "18.04.2018";
    var dParts = dString.split('.');
    var in30Days = new Date(dParts[2] + '/' +
                            dParts[1] + '/' +
                            (+dParts[0] + 10)
                   );
    var endDate =  in30Days.getDate() + "." + (in30Days.getMonth()+1) + "." +in30Days.getFullYear();
    console.log("Now:" + dString + " EndDate: " + endDate);

    for (var d = dString; d <= endDate; d.setDate(d.getDate() + 1)) {
        var loopDay = new Date(d);
        console.log("Day:" + loopDay);
    }

The end date is the start date plus 10 days.

Here is the console log output i receive:

Now:18.04.2018 EndDate: 28.4.2018
Day:Invalid Date

Why the date is invalid. Where is my mistake ?

Body:
 $('#button').on('click',function(){
    var end = $('#end').val()
    var start = $('#start').val()
    var tableau = testdiff(new Date(start),new Date(end));
    console.log(tableau);
  })

  function testdiff(from,to){
    var resultat=[];
    while (from <= to) {
        var dd = from.getDate();
        var mm = from.getMonth()+1;
        var yyyy = from.getFullYear();
        if(dd<10) {dd='0'+dd;}
        if(mm<10){mm='0'+mm;}
        var vDate = yyyy+'-'+mm+'-'+dd;
        resultat.push(vDate);
        from = new Date(from.setDate(from.getDate() + 1));
    }
    return resultat;
}

<div class="my-2 mx-2">
        <div class="col-sm-4">
            <label for="">start</label>
            <input type="date" name="start" id="start" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4">
            <label for=""> end</label>
            <input type="date" name="end" id="end" class="form-control form-control-sm">
        </div>
        <div class="col-sm-4 my-3">
            <button type="button" id="button" class="btn btn-default">clic</button>
        </div>

    </div>

use jquery


问:
Why I get 'statement or delimiter expected, got ...' error for @Table annotation
I just started learning spring boot but I keep running into this error shown below when I set the name in the @Table annotation. I have absolutely no idea what is causing it since I do have the table defined in my schema. My at column annotations seem to work fine so it at least recognizes to columns of the table. Any advice? Thanks.

答:
You are having some SQL dialect injected into this string. Un-inject the language from Alt+Enter Intention action popup menu:

Now, to make this table annotation be resolved into a database table - you should assign a data source to your JPA persistence unit in Persistence tool window:

then navigation will work:


问:
How to get output tensor from a specific layer?
I would like to figure it out if is it possible to get the output from a specific layer using tensorflow lite for android environment.
At the moment I know that using: 'interpreter.run()' we take the "standard" output, but this is not what I'm looking for.
Thanks for any advice.</p>

答:
@Simo I will write here a workaround of this problem. How about saving the part of the model you want to .tflite file. Let me explain myself. Instead of doing below and save the whole model:

```<code># WHOLE MODEL
tflite_model = tf.keras.models.load_model('face_recog.weights.best.hdf5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
tflite_save = converter.convert()
open("face_recog.tflite", "wb").write(tflite_save)
</code>```

You can print the layers of your keras model:

```<code>print([layer.name for layer in keras_model.layers])
Output:
['anchor', 'positive', 'negative', 'model', 'lambda']

print([layer.name for layer in keras_model.get_layer('model').layers])
Output:
['input_1', 'Conv1_pad', 'Conv1', 'bn_Conv1', 'Conv1_relu', 'expanded_conv_depthwise', 'expanded_conv_depthwise_BN', 'expanded_conv_depthwise_relu', 'expanded_conv_project', 'expanded_conv_project_BN', 'block_1_expand', 'block_1_expand_BN', 'block_1_expand_relu', 'block_1_pad', 'block_1_depthwise', 'block_1_depthwise_BN', 'block_1_depthwise_relu', 'block_1_project', 'block_1_project_BN', 'block_2_expand', 'block_2_expand_BN', 'block_2_expand_relu', 'block_2_depthwise', 'block_2_depthwise_BN', 'block_2_depthwise_relu', 'block_2_project', 'block_2_project_BN', 'block_2_add', 'block_3_expand', 'block_3_expand_BN', 'block_3_expand_relu', 'block_3_pad', 'block_3_depthwise', 'block_3_depthwise_BN', 'block_3_depthwise_relu', 'block_3_project', 'block_3_project_BN', 'block_4_expand', 'block_4_expand_BN', 'block_4_expand_relu', 'block_4_depthwise', 'block_4_depthwise_BN', 'block_4_depthwise_relu', 'block_4_project', 'block_4_project_BN', 'block_4_add', 'block_5_expand', 'block_5_expand_BN', 'block_5_expand_relu', 'block_5_depthwise', 'block_5_depthwise_BN', 'block_5_depthwise_relu', 'block_5_project', 'block_5_project_BN', 'block_5_add', 'block_6_expand', 'block_6_expand_BN', 'block_6_expand_relu', 'block_6_pad', 'block_6_depthwise', 'block_6_depthwise_BN', 'block_6_depthwise_relu', 'block_6_project', 'block_6_project_BN', 'block_7_expand', 'block_7_expand_BN', 'block_7_expand_relu', 'block_7_depthwise', 'block_7_depthwise_BN', 'block_7_depthwise_relu', 'block_7_project', 'block_7_project_BN', 'block_7_add', 'block_8_expand', 'block_8_expand_BN', 'block_8_expand_relu', 'block_8_depthwise', 'block_8_depthwise_BN', 'block_8_depthwise_relu', 'block_8_project', 'block_8_project_BN', 'block_8_add', 'block_9_expand', 'block_9_expand_BN', 'block_9_expand_relu', 'block_9_depthwise', 'block_9_depthwise_BN', 'block_9_depthwise_relu', 'block_9_project', 'block_9_project_BN', 'block_9_add', 'block_10_expand', 'block_10_expand_BN', 'block_10_expand_relu', 'block_10_depthwise', 'block_10_depthwise_BN', 'block_10_depthwise_relu', 'block_10_project', 'block_10_project_BN', 'block_11_expand', 'block_11_expand_BN', 'block_11_expand_relu', 'block_11_depthwise', 'block_11_depthwise_BN', 'block_11_depthwise_relu', 'block_11_project', 'block_11_project_BN', 'block_11_add', 'block_12_expand', 'block_12_expand_BN', 'block_12_expand_relu', 'block_12_depthwise', 'block_12_depthwise_BN', 'block_12_depthwise_relu', 'block_12_project', 'block_12_project_BN', 'block_12_add', 'block_13_expand', 'block_13_expand_BN', 'block_13_expand_relu', 'block_13_pad', 'block_13_depthwise', 'block_13_depthwise_BN', 'block_13_depthwise_relu', 'block_13_project', 'block_13_project_BN', 'block_14_expand', 'block_14_expand_BN', 'block_14_expand_relu', 'block_14_depthwise', 'block_14_depthwise_BN', 'block_14_depthwise_relu', 'block_14_project', 'block_14_project_BN', 'block_14_add', 'block_15_expand', 'block_15_expand_BN', 'block_15_expand_relu', 'block_15_depthwise', 'block_15_depthwise_BN', 'block_15_depthwise_relu', 'block_15_project', 'block_15_project_BN', 'block_15_add', 'block_16_expand', 'block_16_expand_BN', 'block_16_expand_relu', 'block_16_depthwise', 'block_16_depthwise_BN', 'block_16_depthwise_relu', 'block_16_project', 'block_16_project_BN', 'Conv_1', 'Conv_1_bn', 'out_relu', 'global_average_pooling2d', 'predictions', 'dense', 'dense_1']
</code>```

And then you can take whatever layer you want from your model and save it to .tflite:

```<code># PART OF MODEL
tflite_model = tf.keras.models.load_model('face_recog.weights.best.hdf5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model.get_layer('model'))
tflite_save = converter.convert()
open("face_recog.tflite", "wb").write(tflite_save)
</code>```

So using the above code the .tflite file will have input tensor = "input_1" and output = "dense_1"

Then inside android you have to use inputs for the specific layer "model" and you will get outputs of the specific shape as when you print the output details in python:

```<code>interpreter = tf.lite.Interpreter('face_recog.tflite')
print(interpreter.get_output_details())
interpreter.get_tensor_details()
</code>```

Android part:

```<code>// Initialize interpreter
@Throws(IOException::class)
private suspend fun initializeInterpreter(app: Application) = withContext(Dispatchers.IO) {
    // Load the TF Lite model from asset folder and initialize TF Lite Interpreter without NNAPI enabled.
    val assetManager = app.assets
    val model = loadModelFile(assetManager, "face_recog_model_layer.tflite")
    val options = Interpreter.Options()
    options.setUseNNAPI(false)
    interpreter = Interpreter(model, options)
    // Reads type and shape of input and output tensors, respectively.
    val imageTensorIndex = 0
    val imageShape: IntArray =
        interpreter.getInputTensor(imageTensorIndex).shape()
    Log.i("INPUT_TENSOR_WHOLE", Arrays.toString(imageShape))
    val imageDataType: DataType =
        interpreter.getInputTensor(imageTensorIndex).dataType()
    Log.i("INPUT_DATA_TYPE", imageDataType.toString())
    val probabilityTensorIndex = 0
    val probabilityShape: IntArray =
        interpreter.getOutputTensor(probabilityTensorIndex).shape()
    Log.i("OUTPUT_TENSOR_SHAPE", Arrays.toString(probabilityShape))
    val probabilityDataType: DataType =
        interpreter.getOutputTensor(probabilityTensorIndex).dataType()
    Log.i("OUTPUT_DATA_TYPE", probabilityDataType.toString())
    Log.i(TAG, "Initialized TFLite interpreter.")

}

@Throws(IOException::class)
private fun loadModelFile(assetManager: AssetManager, filename: String): MappedByteBuffer {
    val fileDescriptor = assetManager.openFd(filename)
    val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
    val fileChannel = inputStream.channel
    val startOffset = fileDescriptor.startOffset
    val declaredLength = fileDescriptor.declaredLength
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}
</code>```

I hope this will help someone. And of course if you need anything else tag me :)

Body:
@Simo I will write here a workaround of this problem. How about saving the part of the model you want to .tflite file. Let me explain myself. Instead of doing below and save the whole model:

# WHOLE MODEL
tflite_model = tf.keras.models.load_model('face_recog.weights.best.hdf5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
tflite_save = converter.convert()
open("face_recog.tflite", "wb").write(tflite_save)

You can print the layers of your keras model:

print([layer.name for layer in keras_model.layers])
Output:
['anchor', 'positive', 'negative', 'model', 'lambda']

print([layer.name for layer in keras_model.get_layer('model').layers])
Output:
['input_1', 'Conv1_pad', 'Conv1', 'bn_Conv1', 'Conv1_relu', 'expanded_conv_depthwise', 'expanded_conv_depthwise_BN', 'expanded_conv_depthwise_relu', 'expanded_conv_project', 'expanded_conv_project_BN', 'block_1_expand', 'block_1_expand_BN', 'block_1_expand_relu', 'block_1_pad', 'block_1_depthwise', 'block_1_depthwise_BN', 'block_1_depthwise_relu', 'block_1_project', 'block_1_project_BN', 'block_2_expand', 'block_2_expand_BN', 'block_2_expand_relu', 'block_2_depthwise', 'block_2_depthwise_BN', 'block_2_depthwise_relu', 'block_2_project', 'block_2_project_BN', 'block_2_add', 'block_3_expand', 'block_3_expand_BN', 'block_3_expand_relu', 'block_3_pad', 'block_3_depthwise', 'block_3_depthwise_BN', 'block_3_depthwise_relu', 'block_3_project', 'block_3_project_BN', 'block_4_expand', 'block_4_expand_BN', 'block_4_expand_relu', 'block_4_depthwise', 'block_4_depthwise_BN', 'block_4_depthwise_relu', 'block_4_project', 'block_4_project_BN', 'block_4_add', 'block_5_expand', 'block_5_expand_BN', 'block_5_expand_relu', 'block_5_depthwise', 'block_5_depthwise_BN', 'block_5_depthwise_relu', 'block_5_project', 'block_5_project_BN', 'block_5_add', 'block_6_expand', 'block_6_expand_BN', 'block_6_expand_relu', 'block_6_pad', 'block_6_depthwise', 'block_6_depthwise_BN', 'block_6_depthwise_relu', 'block_6_project', 'block_6_project_BN', 'block_7_expand', 'block_7_expand_BN', 'block_7_expand_relu', 'block_7_depthwise', 'block_7_depthwise_BN', 'block_7_depthwise_relu', 'block_7_project', 'block_7_project_BN', 'block_7_add', 'block_8_expand', 'block_8_expand_BN', 'block_8_expand_relu', 'block_8_depthwise', 'block_8_depthwise_BN', 'block_8_depthwise_relu', 'block_8_project', 'block_8_project_BN', 'block_8_add', 'block_9_expand', 'block_9_expand_BN', 'block_9_expand_relu', 'block_9_depthwise', 'block_9_depthwise_BN', 'block_9_depthwise_relu', 'block_9_project', 'block_9_project_BN', 'block_9_add', 'block_10_expand', 'block_10_expand_BN', 'block_10_expand_relu', 'block_10_depthwise', 'block_10_depthwise_BN', 'block_10_depthwise_relu', 'block_10_project', 'block_10_project_BN', 'block_11_expand', 'block_11_expand_BN', 'block_11_expand_relu', 'block_11_depthwise', 'block_11_depthwise_BN', 'block_11_depthwise_relu', 'block_11_project', 'block_11_project_BN', 'block_11_add', 'block_12_expand', 'block_12_expand_BN', 'block_12_expand_relu', 'block_12_depthwise', 'block_12_depthwise_BN', 'block_12_depthwise_relu', 'block_12_project', 'block_12_project_BN', 'block_12_add', 'block_13_expand', 'block_13_expand_BN', 'block_13_expand_relu', 'block_13_pad', 'block_13_depthwise', 'block_13_depthwise_BN', 'block_13_depthwise_relu', 'block_13_project', 'block_13_project_BN', 'block_14_expand', 'block_14_expand_BN', 'block_14_expand_relu', 'block_14_depthwise', 'block_14_depthwise_BN', 'block_14_depthwise_relu', 'block_14_project', 'block_14_project_BN', 'block_14_add', 'block_15_expand', 'block_15_expand_BN', 'block_15_expand_relu', 'block_15_depthwise', 'block_15_depthwise_BN', 'block_15_depthwise_relu', 'block_15_project', 'block_15_project_BN', 'block_15_add', 'block_16_expand', 'block_16_expand_BN', 'block_16_expand_relu', 'block_16_depthwise', 'block_16_depthwise_BN', 'block_16_depthwise_relu', 'block_16_project', 'block_16_project_BN', 'Conv_1', 'Conv_1_bn', 'out_relu', 'global_average_pooling2d', 'predictions', 'dense', 'dense_1']

And then you can take whatever layer you want from your model and save it to .tflite:

# PART OF MODEL
tflite_model = tf.keras.models.load_model('face_recog.weights.best.hdf5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model.get_layer('model'))
tflite_save = converter.convert()
open("face_recog.tflite", "wb").write(tflite_save)

So using the above code the .tflite file will have input tensor = "input_1" and output = "dense_1"

Then inside android you have to use inputs for the specific layer "model" and you will get outputs of the specific shape as when you print the output details in python:

interpreter = tf.lite.Interpreter('face_recog.tflite')
print(interpreter.get_output_details())
interpreter.get_tensor_details()

Android part:

// Initialize interpreter
@Throws(IOException::class)
private suspend fun initializeInterpreter(app: Application) = withContext(Dispatchers.IO) {
    // Load the TF Lite model from asset folder and initialize TF Lite Interpreter without NNAPI enabled.
    val assetManager = app.assets
    val model = loadModelFile(assetManager, "face_recog_model_layer.tflite")
    val options = Interpreter.Options()
    options.setUseNNAPI(false)
    interpreter = Interpreter(model, options)
    // Reads type and shape of input and output tensors, respectively.
    val imageTensorIndex = 0
    val imageShape: IntArray =
        interpreter.getInputTensor(imageTensorIndex).shape()
    Log.i("INPUT_TENSOR_WHOLE", Arrays.toString(imageShape))
    val imageDataType: DataType =
        interpreter.getInputTensor(imageTensorIndex).dataType()
    Log.i("INPUT_DATA_TYPE", imageDataType.toString())
    val probabilityTensorIndex = 0
    val probabilityShape: IntArray =
        interpreter.getOutputTensor(probabilityTensorIndex).shape()
    Log.i("OUTPUT_TENSOR_SHAPE", Arrays.toString(probabilityShape))
    val probabilityDataType: DataType =
        interpreter.getOutputTensor(probabilityTensorIndex).dataType()
    Log.i("OUTPUT_DATA_TYPE", probabilityDataType.toString())
    Log.i(TAG, "Initialized TFLite interpreter.")

}

@Throws(IOException::class)
private fun loadModelFile(assetManager: AssetManager, filename: String): MappedByteBuffer {
    val fileDescriptor = assetManager.openFd(filename)
    val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
    val fileChannel = inputStream.channel
    val startOffset = fileDescriptor.startOffset
    val declaredLength = fileDescriptor.declaredLength
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}

I hope this will help someone. And of course if you need anything else tag me :)


问:
Is it possible for a computer to "learn" a regular expression by user-provided examples?
Is it possible for a computer to "learn" a regular expression by user-provided examples?

To clarify:

I do not want to learn regular expressions.

I want to create a program which "learns" a regular expression from examples which are interactively provided by a user, perhaps by selecting parts from a text or selecting begin or end markers.

Is it possible? Are there algorithms, keywords, etc. which I can Google for?

EDIT: Thank you for the answers, but I'm not interested in tools which provide this feature. I'm looking for theoretical information, like papers, tutorials, source code, names of algorithms, so I can create something for myself.

答:
There's a language dedicated to problems like this, based on prolog. It's called progol.

As others have mentioned, the basic idea is inductive learning, often called ILP (inductive logic programming) in AI circles.

Second link is the wiki article on ILP, which contains a lot of useful source material if you're interested in learning more about the topic.

OwnerDisplayName: DR

LastEditorDisplayName: DR

OwnerDisplayName: patros

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: patros


问:
How to create the following XML tag through DOM in Java
```<code><tableCategory>
        <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
</tableCategory>
</code>```

In the above xml tag, I want to add one more item as follows-

```<code><item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
</code>```

So finally the XML tag will look like-

```<code><tableCategory>
            <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
                <item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
 </tableCategory>
</code>```

I am getting the tag -

```<code>Element paletteElement = (Element) doc.getElementsByTagName("tableCategory").item(0); //tag
</code>```

But not getting the clue after that.

答:
Assuming you are using javax.xml.parsers, element.appendChild() will do.

[edited]

In case, you are looking for how to create a new Element, below is an example snippet

```<code>Element newElem = doc.createElement("item");
newElem.setAttribute(...);
...
...
elem.addChild(newElem);
</code>```

Body:
<tableCategory>
        <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
</tableCategory>

In the above xml tag, I want to add one more item as follows-

<item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>

So finally the XML tag will look like-

<tableCategory>
            <item app_name="APPNAME1i" desc="BDESC1" lang="1ODDD"/>
                <item app_name="APPNAME2" desc="DESC2" lang="2ODDD"/>
 </tableCategory>

I am getting the tag -

Element paletteElement = (Element) doc.getElementsByTagName("tableCategory").item(0); //tag

But not getting the clue after that.

Body:
Assuming you are using javax.xml.parsers, element.appendChild() will do.

[edited]

In case, you are looking for how to create a new Element, below is an example snippet

Element newElem = doc.createElement("item");
newElem.setAttribute(...);
...
...
elem.addChild(newElem);


问:
Error creating bean named `conversionServicePostProcessor` when using spring-boot-admin-server
I was trying to enable Spring boot admin server for my application. The default settings work perfectly fine but when I attempt to enable security, I am getting following error:

APPLICATION FAILED TO START

Description:

The bean 'conversionServicePostProcessor', defined in class path
  resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class],
  could not be registered. A bean with that name has already been
  defined in class path resource
  [org/springframework/security/config/annotation/web/reactive/WebFluxSecurityConfiguration.class]
  and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

Process finished with exit code 1

I am using the latest SNAPSHOT version of spring-boot-admin-starter-server (2.2.0-SNAPSHOT). Here is my security configuration:

```<code>@EnableAdminServer
@EnableWebFluxSecurity
@Configuration(proxyBeanMethods = false)
class AdminServerSecurityConfigurations(val adminServerProperties: AdminServerProperties) {

    @Bean
    fun adminServerSecurityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain = http
            // @formatter:off
            .authorizeExchange()
                .pathMatchers("${adminServerProperties.contextPath}/assets/**").permitAll()
                .pathMatchers("${adminServerProperties.contextPath}/login").permitAll()
                .anyExchange().authenticated().and()
            .formLogin().loginPage("${adminServerProperties.contextPath}/login").and()
            .logout().logoutUrl("${adminServerProperties.contextPath}/logout").and()
            .httpBasic().and()
            // @formatter:on
            .csrf().disable()
            .build()

    @Bean
    fun notifyLogger(instanceRepository: InstanceRepository) = LoggingNotifier(instanceRepository)

}
</code>```

答:
I had the same issue and was able solve it by adding

```<code>spring.main.allow-bean-definition-overriding=true
</code>```

to my application.properties.

Sounds like a workaround and it was also only necessary if I deployed it as WAR -- as a standalone application the exception never occured.

Body:
I was trying to enable Spring boot admin server for my application. The default settings work perfectly fine but when I attempt to enable security, I am getting following error:

APPLICATION FAILED TO START

Description:

The bean 'conversionServicePostProcessor', defined in class path
  resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class],
  could not be registered. A bean with that name has already been
  defined in class path resource
  [org/springframework/security/config/annotation/web/reactive/WebFluxSecurityConfiguration.class]
  and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

Process finished with exit code 1

I am using the latest SNAPSHOT version of spring-boot-admin-starter-server (2.2.0-SNAPSHOT). Here is my security configuration:

@EnableAdminServer
@EnableWebFluxSecurity
@Configuration(proxyBeanMethods = false)
class AdminServerSecurityConfigurations(val adminServerProperties: AdminServerProperties) {

    @Bean
    fun adminServerSecurityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain = http
            // @formatter:off
            .authorizeExchange()
                .pathMatchers("${adminServerProperties.contextPath}/assets/**").permitAll()
                .pathMatchers("${adminServerProperties.contextPath}/login").permitAll()
                .anyExchange().authenticated().and()
            .formLogin().loginPage("${adminServerProperties.contextPath}/login").and()
            .logout().logoutUrl("${adminServerProperties.contextPath}/logout").and()
            .httpBasic().and()
            // @formatter:on
            .csrf().disable()
            .build()

    @Bean
    fun notifyLogger(instanceRepository: InstanceRepository) = LoggingNotifier(instanceRepository)

}

Body:
I had the same issue and was able solve it by adding

spring.main.allow-bean-definition-overriding=true

to my application.properties.

Sounds like a workaround and it was also only necessary if I deployed it as WAR -- as a standalone application the exception never occured.


问:
Flutter .apk is built but is not getting installed in the device/emulator
I have set a custom outputFileName in the module level gradle file. When I try to run the application by pressing the play button (or using menu commands for debu/release build), the apk is getting built but the application is not getting installed on the connected device.

Getting the following error.

Finished with error: Gradle build failed to produce an .apk file. It's likely that this file was generated under C:\Users\BnayA\Work\Office\sangrahapp\build, but the tool couldn't find it.

I googled the solution for it, but nothing helped me to fix it.

Below is my app/module level Gradle config.

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

ant.condition(property: 'os', value: 'windows') {
    os(family: 'windows')
}
ant.condition(property: 'os', value: 'unix') {
    os(family: 'unix')
}

// Based on http://stackoverflow.com/questions/17097263#24121734
def getMasterCommitCount = { ->
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            switch (ant.properties.os) {
                case 'windows':
                    commandLine 'cmd', '/c', 'git', 'rev-list', '--first-parent', '--count', 'master'
                    break
                case 'unix':
                    commandLine 'git', 'rev-list', '--first-parent', '--count', 'master'
                    break
            }
            standardOutput = stdout
        }
        return Integer.parseInt(stdout.toString().trim())
    } catch (ignored) {
        return -1
    }
}

def getVersionName = { ->
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            switch (ant.properties.os) {
                case 'windows':
                    commandLine 'cmd', '/c', 'git', 'describe', '--tags', '--dirty', '--always'
                    break
                case 'unix':
                    commandLine 'git', 'describe', '--tags', '--dirty', '--always'
                    break
            }
            standardOutput = stdout
        }
        return stdout.toString().trim()
    } catch (ignored) {
        return null
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    compileSdkVersion 29

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "abc.def.ghi"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode getMasterCommitCount()
        versionName getVersionName()
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        archivesBaseName = 'abc'
    }

    buildTypes {
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix '_debug'
        }

        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile(
                    'proguard-android-optimize.txt'),
                    'proguard-rules.pro'
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            outputFileName = new File(outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))
        }
    }

    splits {
        abi {
            universalApk true
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
}
</code>```

答:
Try to replace

```<code>outputFileName = new File(outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))

</code>```

with the following code

```<code> outputFileName = new File(
             output.outputFile.parent,
             outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))
</code>```

Update:
replace this

```<code>splits {
        abi {
            universalApk true
        }
    }
</code>```

with the following

```<code>splits {
        abi {
            enable true
            reset()
            universalApk false
        }
    }
</code>```

Please add signing config in debug also.

```<code>signingConfig signingConfigs.debug
</code>```

Body:
I have set a custom outputFileName in the module level gradle file. When I try to run the application by pressing the play button (or using menu commands for debu/release build), the apk is getting built but the application is not getting installed on the connected device.

Getting the following error.

Finished with error: Gradle build failed to produce an .apk file. It's likely that this file was generated under C:\Users\BnayA\Work\Office\sangrahapp\build, but the tool couldn't find it.

I googled the solution for it, but nothing helped me to fix it.

Below is my app/module level Gradle config.

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

ant.condition(property: 'os', value: 'windows') {
    os(family: 'windows')
}
ant.condition(property: 'os', value: 'unix') {
    os(family: 'unix')
}

// Based on http://stackoverflow.com/questions/17097263#24121734
def getMasterCommitCount = { ->
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            switch (ant.properties.os) {
                case 'windows':
                    commandLine 'cmd', '/c', 'git', 'rev-list', '--first-parent', '--count', 'master'
                    break
                case 'unix':
                    commandLine 'git', 'rev-list', '--first-parent', '--count', 'master'
                    break
            }
            standardOutput = stdout
        }
        return Integer.parseInt(stdout.toString().trim())
    } catch (ignored) {
        return -1
    }
}

def getVersionName = { ->
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            switch (ant.properties.os) {
                case 'windows':
                    commandLine 'cmd', '/c', 'git', 'describe', '--tags', '--dirty', '--always'
                    break
                case 'unix':
                    commandLine 'git', 'describe', '--tags', '--dirty', '--always'
                    break
            }
            standardOutput = stdout
        }
        return stdout.toString().trim()
    } catch (ignored) {
        return null
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    compileSdkVersion 29

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "abc.def.ghi"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode getMasterCommitCount()
        versionName getVersionName()
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        archivesBaseName = 'abc'
    }

    buildTypes {
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix '_debug'
        }

        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile(
                    'proguard-android-optimize.txt'),
                    'proguard-rules.pro'
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            outputFileName = new File(outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))
        }
    }

    splits {
        abi {
            universalApk true
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
}

Body:
Try to replace

outputFileName = new File(outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))

with the following code

 outputFileName = new File(
             output.outputFile.parent,
             outputFileName.replace(".apk", "-${defaultConfig.versionName}.apk"))

Update:
replace this

splits {
        abi {
            universalApk true
        }
    }

with the following

splits {
        abi {
            enable true
            reset()
            universalApk false
        }
    }

Please add signing config in debug also.

signingConfig signingConfigs.debug


问:
com.teamdev.jxbrowser.internal.ChromiumExtractorException: Failed to extract Chromium binaries into x folder
Recently migrated to JxBrowser 7.0 and i have the following error coming every time i try to start the application .

```<code>com.teamdev.jxbrowser.internal.ChromiumExtractorException: Failed to extract Chromium binaries into C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0
    at jxbrowser@7.0/com.teamdev.jxbrowser.internal.ChromiumExtractor.extract(ChromiumExtractor.java:45)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.internal.EngineImpl.extractChromiumBinaries(EngineImpl.java:386)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.internal.EngineImpl.newInstance(EngineImpl.java:156)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.Engine.newInstance(Engine.java:96)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserTabController.initialize(WebBrowserTabController.java:191)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2591)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserTabController.<init>(WebBrowserTabController.java:166)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.createNewTab(WebBrowserController.java:180)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.createAndAddNewTab(WebBrowserController.java:161)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.initialize(WebBrowserController.java:116)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2591)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.<init>(WebBrowserController.java:99)
    at XR3Player/com.goxr3plus.xr3player.application.MainLoader.lambda$startPart2$8(MainLoader.java:373)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:835)
</code>```

It says caused by :

```<code>Caused by: java.io.FileNotFoundException: chromium-win64.7z, chromium-win32.7z
    ... 44 more
</code>```

where is this coming from ? My project is a Maven project and i have added all the needed dependencies and on the start of application i have added the license key and the directory i want to browser to have it's files :

```<code>static {

    // Chromium Extract Location Dir
    System.setProperty("jxbrowser.license.key", "license_key");
    System.setProperty("jxbrowser.chromium.dir",
        DatabaseTool.getAbsoluteDatabaseParentFolderPathWithSeparator() + "Chrome" + "7.0");
}
</code>```

Enabling JxBrowser Logger :

```<code>01:19:49.837 DEBUG Verifying Chromium binaries...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll... [FAIL] File does not exist
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll... [FAIL] File does not exist
01:19:49.839 DEBUG Verifying Chromium binaries... [FAIL]
01:19:49.839 DEBUG Finding Chromium binaries in JARs...
01:19:49.839 DEBUG Finding WIN_64...
01:19:49.840 DEBUG Finding WIN_64... [FAIL]
01:19:49.840 DEBUG Finding WIN_32...
01:19:49.840 DEBUG Finding WIN_32... [FAIL]
</code>```

Maven Dependencies :

```<code><!-- CHROMIUM BROWSER -->
<dependency>
    <groupId>com.teamdev.jxbrowser</groupId>
    <artifactId>jxbrowser-win64</artifactId>
    <version>7.0</version>
</dependency>

<dependency>
    <groupId>com.teamdev.jxbrowser</groupId>
    <artifactId>jxbrowser-javafx</artifactId>
    <version>7.0</version>
</dependency>
</code>```

答: I had the same bug when i added the OS specific jar in Intellij classpath. What i have done to fix it is to remove it and put it back again. Intellij don't recognize it and display a popup with options to select what kind of jar it is. then select classes.</p>

Body:
Recently migrated to JxBrowser 7.0 and i have the following error coming every time i try to start the application .

com.teamdev.jxbrowser.internal.ChromiumExtractorException: Failed to extract Chromium binaries into C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0
    at jxbrowser@7.0/com.teamdev.jxbrowser.internal.ChromiumExtractor.extract(ChromiumExtractor.java:45)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.internal.EngineImpl.extractChromiumBinaries(EngineImpl.java:386)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.internal.EngineImpl.newInstance(EngineImpl.java:156)
    at jxbrowser@7.0/com.teamdev.jxbrowser.engine.Engine.newInstance(Engine.java:96)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserTabController.initialize(WebBrowserTabController.java:191)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2591)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserTabController.<init>(WebBrowserTabController.java:166)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.createNewTab(WebBrowserController.java:180)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.createAndAddNewTab(WebBrowserController.java:161)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.initialize(WebBrowserController.java:116)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2591)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at XR3Player/com.goxr3plus.xr3player.controllers.chromium.WebBrowserController.<init>(WebBrowserController.java:99)
    at XR3Player/com.goxr3plus.xr3player.application.MainLoader.lambda$startPart2$8(MainLoader.java:373)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:835)

It says caused by :

Caused by: java.io.FileNotFoundException: chromium-win64.7z, chromium-win32.7z
    ... 44 more

where is this coming from ? My project is a Maven project and i have added all the needed dependencies and on the start of application i have added the license key and the directory i want to browser to have it's files :

static {

    // Chromium Extract Location Dir
    System.setProperty("jxbrowser.license.key", "license_key");
    System.setProperty("jxbrowser.chromium.dir",
        DatabaseTool.getAbsoluteDatabaseParentFolderPathWithSeparator() + "Chrome" + "7.0");
}

Enabling JxBrowser Logger :

01:19:49.837 DEBUG Verifying Chromium binaries...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll... [FAIL] File does not exist
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll...
01:19:49.838 DEBUG Verifying C:\Personal Projects\Github\XR3Player\target\classes\Chrome7.0\libEGL.dll... [FAIL] File does not exist
01:19:49.839 DEBUG Verifying Chromium binaries... [FAIL]
01:19:49.839 DEBUG Finding Chromium binaries in JARs...
01:19:49.839 DEBUG Finding WIN_64...
01:19:49.840 DEBUG Finding WIN_64... [FAIL]
01:19:49.840 DEBUG Finding WIN_32...
01:19:49.840 DEBUG Finding WIN_32... [FAIL]

Maven Dependencies :

<dependency>
    <groupId>com.teamdev.jxbrowser</groupId>
    <artifactId>jxbrowser-win64</artifactId>
    <version>7.0</version>
</dependency>

<dependency>
    <groupId>com.teamdev.jxbrowser</groupId>
    <artifactId>jxbrowser-javafx</artifactId>
    <version>7.0</version>
</dependency>


问:
Control flow statements. How many years should pass until goal money
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}
</code>```

Test input: 100 15 120

Correct output: 2

Your code output: 1

答:
Try making changes as shown below.</p>

```<code>int years = 0;
while (goal > money) {
    money = money + money * (percent / 100);
    ++years;
}
</code>```

Body:
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}

Test input: 100 15 120

Correct output: 2

Your code output: 1

Body:
Try making changes as shown below.

int years = 0;
while (goal > money) {
    money = money + money * (percent / 100);
    ++years;
}


问:
Problems with if ....==NULL in C
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!</p>

```<code>FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}
</code>```

答:
1.

"It Enters here as well, but it should not do that or?????"

No, It shouldn´t. If both pointers are NULL the opening of the streams to ANMAL.DAT were not successful, neither in w+b nor in r+b mode. Proof if the file really exist in the directory of the executable. Else try to use the entire path from the root directory to the file.

"The problem is if the file exists it still overwrites it."

Why do you know that the file is really overwritten in a proper manner?

Since if ((pointer =fopen(name, "r+b")) == NULL) and if ((pointer = fopen(name, "w+b"))== NULL) both fail, it seems that the ANMAL.DAT does not exist where fopen() searches for it or otherwise an error occurs when trying to open it (maybe has incorrect format or is corrupted?).

Place perror(name) in the error routine to check if errno was set to indicate an error at name.

2.

In the error routine: exit(0) is not correct if an error has happened. Use exit(EXIT_FAILURE).

Side note:

You have another prototype for the function openFil-> FILE *openFil(FILE *open, char namn[]); inside of main, which is redundant.

Also the identifier of the second parameter is different in the prototype before main to the identifier at the definition of openFil, namn in comparison to name.

Title: Problems with if ....==NULL in C

Body:
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!

FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}