问:
Using static functions of different class in worker class for experimenting
I have two classes which are inheriting from some virtual base class

```<code>class A : public BaseClass {
    public:
       static int foo(){ ... };

       static void bar(){ ... };
};

class B : BaseClass {
    public:
       static int foo(){ ... };

       static void bar(){ ... };
};
</code>```

I have another class Worker that is exposed to the client and makes use of these two classes

```<code>class Worker{
    public:
       static void doFoo(){
           int result = A::foo();
           ...
       }

       static void doBar(){
           A::bar();
       }
}
</code>```

I can either use A in the Worker class or B. Right now, if I have to plug the class B in Worker class, I will have to make changes in all the functions in the Worker.

```<code>class Worker{
    public:
       static void doFoo(){
           int result = B::foo();
           ...
       }

       static void doBar(){
           B::bar();
       }
}
</code>```

Is there a way I can keep the methods static, not create an object of either A, B, or the Worker class and still be able to just make a few minor changes in the code and change the plug from A to B.

I thought of using templates (didn't explore it) but I don't want to let the user know of A, or B.

Thanks

答:
You could make a class template like this:

```<code>template <typename T>
class Worker_T {
    public:
       static void doFoo(){
           int result = T::foo();
       }

       static void doBar(){
           T::bar();
       }
};
</code>```

and then to choose which class to actually use, you only have to choose one of the following:

```<code>using Worker = Worker_T<A>;
</code>```

or

```<code>using Worker = Worker_T<B>;
</code>```

and the user of Worker doesn't need to know about A or B.

Body:
I have two classes which are inheriting from some virtual base class

class A : public BaseClass {
    public:
       static int foo(){ ... };

       static void bar(){ ... };
};

class B : BaseClass {
    public:
       static int foo(){ ... };

       static void bar(){ ... };
};

I have another class Worker that is exposed to the client and makes use of these two classes

class Worker{
    public:
       static void doFoo(){
           int result = A::foo();
           ...
       }

       static void doBar(){
           A::bar();
       }
}

I can either use A in the Worker class or B. Right now, if I have to plug the class B in Worker class, I will have to make changes in all the functions in the Worker.

class Worker{
    public:
       static void doFoo(){
           int result = B::foo();
           ...
       }

       static void doBar(){
           B::bar();
       }
}

Is there a way I can keep the methods static, not create an object of either A, B, or the Worker class and still be able to just make a few minor changes in the code and change the plug from A to B.

I thought of using templates (didn't explore it) but I don't want to let the user know of A, or B.

Thanks

Body:
You could make a class template like this:

template <typename T>
class Worker_T {
    public:
       static void doFoo(){
           int result = T::foo();
       }

       static void doBar(){
           T::bar();
       }
};

and then to choose which class to actually use, you only have to choose one of the following:

using Worker = Worker_T<A>;

or

using Worker = Worker_T<B>;

and the user of Worker doesn't need to know about A or B.


来源: stackexchange

问:
I'm having some trouble while coding with two functions
I am trying to make a currency calculator on python:

```<code>print("Please choose which currency you want to convert:")
print("A - Korean Won to US Dollar (Exchange Rate: 0.000905)")
print("B - Korean Won to Euro (Exchange Rate: 0.000807350908)")
print("C - Korean Won to Japanese Yen (Exchange Rate: 0.0919061643)")
print("D - Korean Won to Chinese RMB (Exchange Rate: 0.00603703605)")
print("E - Quit ")

A=0
B=0
C=0
D=0

usd = 0.000905
eur = 0.000807350908
yen = 0.0919061643
rmb = 0.00603703605

def main():
    (option, amount) = Input()
    Output(totalamount)

def Input():
    option = eval(input("Enter your option: "))
    amount = eval(input("Enter the amoutn in Korean Won: "))
    if option == "A":
        totalamount = (amount * usd)
        print (amount +"Won equals to "+totalamount+" USD")
    elif option== "B":
        totalamount = (amount * eur)
        print (amount +"Won equals to "+totalamount+" Euro")
    elif option== "C":
        totalamount = (amount * yen)
        print (amount +"Won equals to "+totalamount+" Yen")
    elif option== "D":
        totalamount = (amount * rmb)
        print (amount +"Won equals to "+totalamount+" Chinese RMB")
    else:
        quit

main()
</code>```

I am still learning how to use python, but  I am wondering why I get this error whenever I run the program:

```<code>TypeError: cannot unpack non-iterable NoneType object
</code>```

How could I fix this?

答:
You are returning nothing and putting the output None in two different variables. This is not right.
at the end of the funciton add

```<code>return option, amount
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a currency calculator on python:

print("Please choose which currency you want to convert:")
print("A - Korean Won to US Dollar (Exchange Rate: 0.000905)")
print("B - Korean Won to Euro (Exchange Rate: 0.000807350908)")
print("C - Korean Won to Japanese Yen (Exchange Rate: 0.0919061643)")
print("D - Korean Won to Chinese RMB (Exchange Rate: 0.00603703605)")
print("E - Quit ")

A=0
B=0
C=0
D=0

usd = 0.000905
eur = 0.000807350908
yen = 0.0919061643
rmb = 0.00603703605

def main():
    (option, amount) = Input()
    Output(totalamount)

def Input():
    option = eval(input("Enter your option: "))
    amount = eval(input("Enter the amoutn in Korean Won: "))
    if option == "A":
        totalamount = (amount * usd)
        print (amount +"Won equals to "+totalamount+" USD")
    elif option== "B":
        totalamount = (amount * eur)
        print (amount +"Won equals to "+totalamount+" Euro")
    elif option== "C":
        totalamount = (amount * yen)
        print (amount +"Won equals to "+totalamount+" Yen")
    elif option== "D":
        totalamount = (amount * rmb)
        print (amount +"Won equals to "+totalamount+" Chinese RMB")
    else:
        quit

main()

I am still learning how to use python, but  I am wondering why I get this error whenever I run the program:

TypeError: cannot unpack non-iterable NoneType object

How could I fix this?

Body:
You are returning nothing and putting the output None in two different variables. This is not right.
at the end of the funciton add

return option, amount


问:
How to make UITableView appear from bottom to top when scroll?
I'm looking just for general scenario.The idea is when app launches user can see only first cell of UITableView at the bottom of UIViewController. When user scrolls up full table appears and when scrolls down only first cell is displayed again. Something similar like keyboard in Facebook messenger app, but with tableView. For now I added tableView as subview to scrollView, but problem is tableView appears from top to bottom, and I'm looking for solution how to make this work upside down.. So, tableView have to appear from bottom to top of UIViewController. </p>

答:
I understand what you want to do.
In general, UITableView shows cells from top to bottom.

You can add transform in tableview:

```<code>tableView.transform = CGAffineTransform(scaleX: 1, y: -1)
</code>```

Then your tableview will show the cells from bottom to top and you can scroll tableview from bottom to top.
But cells will be transformed as tableview, so you have to add same transform to cells also.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")

    **cell.transform = tableView.transform**

    return cell
}
</code>```

All done. Hope to helpful!

ContentLicense: CC BY-SA 3.0

Body:
I understand what you want to do.
In general, UITableView shows cells from top to bottom.

You can add transform in tableview:

tableView.transform = CGAffineTransform(scaleX: 1, y: -1)

Then your tableview will show the cells from bottom to top and you can scroll tableview from bottom to top.
But cells will be transformed as tableview, so you have to add same transform to cells also.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")

    **cell.transform = tableView.transform**

    return cell
}

All done. Hope to helpful!


问:
config.properties file if not exist, how to pass a message in console and continue to next setup without throwing an exception
```<code>public static String readProperty(String property) {
    Properties prop;
    String value = null;
    try {
        prop = new Properties();
        prop.load(new FileInputStream(new File("config.properties")));

        value = prop.getProperty(property);

        if (value == null || value.isEmpty()) {
            throw new Exception("Value not set or empty");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return value;
}
</code>```

I need to check if config.properties exist before loading - if not then just send soft warning message in console system.out.println("config.properties not found")

答:
FileInputStream throws FileNotFoundException

if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

you can catch FileNotFoundException and print your soft warning. for example:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class PropTest
{
        public static String readProperty(String property)
        {
                try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
                        Properties prop = new Properties();
                        prop.load(f);
                        return prop.getProperty(property);

                } catch (FileNotFoundException e) {
                        System.out.println("config.properties not found");
                } catch (Exception e) {
                        e.printStackTrace();
                }

                return null;
        }

        public static void main(String[] args)
        {
                String value = readProperty("foo.bar");
                System.out.println(value);

                value = readProperty("foo.baz");
                System.out.println(value);
        }
}
</code>```

the method readProperty() now returns null if the property is not set or an error occurs while reading the properties file and it also prints a message if the file doesn't exists:

```<code>$ javac PropTest.java
$ java PropTest
config.properties not found
config.properties not found
$ echo "foo.bar=Hello world" > config.properties
$ java PropTest
Hello world
null
$
</code>```

the line:

```<code>try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
</code>```

uses what is called a try-with-resources which automatically closes the file when the code has done with it.

Body:
public static String readProperty(String property) {
    Properties prop;
    String value = null;
    try {
        prop = new Properties();
        prop.load(new FileInputStream(new File("config.properties")));

        value = prop.getProperty(property);

        if (value == null || value.isEmpty()) {
            throw new Exception("Value not set or empty");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return value;
}

I need to check if config.properties exist before loading - if not then just send soft warning message in console system.out.println("config.properties not found")

Body:
FileInputStream throws FileNotFoundException

if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

you can catch FileNotFoundException and print your soft warning. for example:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class PropTest
{
        public static String readProperty(String property)
        {
                try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
                        Properties prop = new Properties();
                        prop.load(f);
                        return prop.getProperty(property);

                } catch (FileNotFoundException e) {
                        System.out.println("config.properties not found");
                } catch (Exception e) {
                        e.printStackTrace();
                }

                return null;
        }

        public static void main(String[] args)
        {
                String value = readProperty("foo.bar");
                System.out.println(value);

                value = readProperty("foo.baz");
                System.out.println(value);
        }
}

the method readProperty() now returns null if the property is not set or an error occurs while reading the properties file and it also prints a message if the file doesn't exists:

$ javac PropTest.java
$ java PropTest
config.properties not found
config.properties not found
$ echo "foo.bar=Hello world" > config.properties
$ java PropTest
Hello world
null
$

the line:

try (FileInputStream f = new FileInputStream(new File("config.properties"))) {

uses what is called a try-with-resources which automatically closes the file when the code has done with it.


问:
Changing the format of date in the Date object
I am using Bootstrap 4. I am writing two functions "saveIssue" and "fetchIssue". The saveIssue function takes the details of the form filled through HTML and stores them in localStorage.In the function, it also notes the time of saving the issues with the new Date() object. fetchIssue function takes the details from localStorage and displays them on screen. While displaying the date of issue obtained through the new Date() object, it is displaying it in the format like 2020-06-02T14:51:21.482Z. How can I just display it in a more generalized form and also not int GMT?

1)fetchIssue function

```<code>function fetchIssues () {
var issues=JSON.parse(localStorage.getItem('issues'));
var I;
for(i=0;i<issues.length;i++)
{
    var id=issues[i].id;
    var description=issues[i].description;
    var severity=issues[i].severity;
    var assignto=issues[i].assignto;
    var status=issues[i].status;
    var deadline=issues[i].deadline;
    var started=issues[i].started;
if(status=="Open")
  {
document.getElementById('issuesList').innerHTML+='<div class="well">'+'<h5> Issue ID : '+ id+'</h5>'
+'<h4><span class="label label-info">'+ status +'</span></h4>'
+'<h3><span class="glyphicon glyphicon-paste"></span>'+"     "+  description + '</h3>'
+ '<p><span class="glyphicon glyphicon-bell"></span>'+'     '+ severity+'         '
+'<span class="glyphicon glyphicon-user"></span>'+'     '+ assignto + '</p>'+'   '
+'<p><span class="glyphicon glyphicon-calendar"></span>'+'  '+'Issued on :'+' '+started+'</p>'
+'<p><span class="glyphicon glyphicon-time"></span>'+'  '+'Deadline :'+' '+deadline+'</p>'
+'<button type="button" class="btn btn-success" onclick="Closed(\''+i+'\')">Close</button>'+' '
+'<button type="button" class="btn btn-danger" onclick="Deleted(\''+i+'\')">Delete</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }

else
  {
document.getElementById('issuesList').innerHTML+='<div class="well">'+'<h5> Issue ID : '+ id+'</h5>'
+'<h4><span class="label label-warning">'+ status +'</span></h4>'
+'<h3><span class="glyphicon glyphicon-paste"></span>'+"     "+  description + '</h3>'
+ '<p><span class="glyphicon glyphicon-time"></span>'+'     '+ severity+'         '
+'<span class="glyphicon glyphicon-user"></span>'+'     '+ assignto + '</p>'
+'<button type="button" class="btn btn-info" onclick="Reopened(\''+i+'\')">Reopen</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }
}
}
</code>```

2)saveIssue funtion

```<code>function saveIssue(e)
{
var id=chance.guid()
var description = document.getElementById("issueDescInput").value;
var severity = document.getElementById("issueSeverityInput").value;
var assignto = document.getElementById("issueAssignedToInput").value;
var status="Open";
var deadline=document.getElementById("deadline").value;
var started=new Date();
var summarized={
    id,
    description,
    severity,
    assignto,
    status,
    deadline,
    started
}
var final=JSON.stringify(summarized);
if(localStorage.getItem('issues')===null)
{
    var issues=[];
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
else
{
    var issues = JSON.parse(localStorage.getItem('issues'));
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
e.preventDefault();
window.location.reload();
}
</code>```

答:
You can format the date in any way you would like by doing a couple of steps:

```<code>let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth() + 1 // January is Month 0, so we add one
let currentDay = currentDate.getDay();
</code>```

These allow you to get the current date (variable currentDate) and extract different information from it (year, month, day). Now you can format it in your way:

yyyy-mm-dd:

```<code>
    if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
    }

    if (currentMonth < 10){
        currentMonth = '0' + currentMonth
    }

let newDate = currentYear + "-" + currentMonth + "-" + currentDay;
</code>```

This will display the date in local time. If you want it in UTC Time:

```<code>let currentDate = new Date();
let currentYear = currentDate.getFullUTCYear();
let currentMonth = currentDate.getUTCMonth() + 1 // January is Month 0, so we add one
let currentDay = currentDate.getUTCDay();
</code>```

And extract:

yyyy-mm-dd:

```<code>    if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
    }

    if (currentMonth < 10){
        currentMonth = '0' + currentMonth
    }

let newDate = currentYear + "-" + currentMonth + "-" + currentDay;
</code>```

See it in action:

function showDate() {

  let currentDate = new Date();
  let currentYear = currentDate.getFullYear();
  let currentMonth = currentDate.getMonth() + 1 // January is Month 0, so we add one
  let currentDay = currentDate.getDay();

     if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
     }

     if (currentMonth < 10){
        currentMonth = '0' + currentMonth
     }

  let newDate = currentYear + "-" + currentMonth + "-" + currentDay;

  document.getElementById('seeDate').innerHTML = newDate;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="showDate()">See the date</button>

<div id="seeDate"></div></code>```

You can also you the toLocaleDateString(), toDateString(), toISOString(), or toLocaleString() for easier methods. But I would stick to the ones above because are able to easily change the format in seconds.

I hope this helps!

Body:
I am using Bootstrap 4. I am writing two functions "saveIssue" and "fetchIssue". The saveIssue function takes the details of the form filled through HTML and stores them in localStorage.In the function, it also notes the time of saving the issues with the new Date() object. fetchIssue function takes the details from localStorage and displays them on screen. While displaying the date of issue obtained through the new Date() object, it is displaying it in the format like 2020-06-02T14:51:21.482Z. How can I just display it in a more generalized form and also not int GMT?

1)fetchIssue function

function fetchIssues () {
var issues=JSON.parse(localStorage.getItem('issues'));
var I;
for(i=0;i<issues.length;i++)
{
    var id=issues[i].id;
    var description=issues[i].description;
    var severity=issues[i].severity;
    var assignto=issues[i].assignto;
    var status=issues[i].status;
    var deadline=issues[i].deadline;
    var started=issues[i].started;
if(status=="Open")
  {
document.getElementById('issuesList').innerHTML+='
'+'
 Issue ID : '+ id+'
'
+'
'+ status +'
'
+'
'+"     "+  description + '
'
+ '
'+'     '+ severity+'         '
+''+'     '+ assignto + '
'+'   '
+'
'+'  '+'Issued on :'+' '+started+'
'
+'
'+'  '+'Deadline :'+' '+deadline+'
'
+'<button type="button" class="btn btn-success" onclick="Closed(\''+i+'\')">Close</button>'+' '
+'<button type="button" class="btn btn-danger" onclick="Deleted(\''+i+'\')">Delete</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }

else
  {
document.getElementById('issuesList').innerHTML+='
'+'
 Issue ID : '+ id+'
'
+'
'+ status +'
'
+'
'+"     "+  description + '
'
+ '
'+'     '+ severity+'         '
+''+'     '+ assignto + '
'
+'<button type="button" class="btn btn-info" onclick="Reopened(\''+i+'\')">Reopen</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }
}
}

2)saveIssue funtion

function saveIssue(e)
{
var id=chance.guid()
var description = document.getElementById("issueDescInput").value;
var severity = document.getElementById("issueSeverityInput").value;
var assignto = document.getElementById("issueAssignedToInput").value;
var status="Open";
var deadline=document.getElementById("deadline").value;
var started=new Date();
var summarized={
    id,
    description,
    severity,
    assignto,
    status,
    deadline,
    started
}
var final=JSON.stringify(summarized);
if(localStorage.getItem('issues')===null)
{
    var issues=[];
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
else
{
    var issues = JSON.parse(localStorage.getItem('issues'));
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
e.preventDefault();
window.location.reload();
}

Body:
You can format the date in any way you would like by doing a couple of steps:

let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth() + 1 // January is Month 0, so we add one
let currentDay = currentDate.getDay();

These allow you to get the current date (variable currentDate) and extract different information from it (year, month, day). Now you can format it in your way:

yyyy-mm-dd:

    if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
    }

    if (currentMonth < 10){
        currentMonth = '0' + currentMonth
    }

let newDate = currentYear + "-" + currentMonth + "-" + currentDay;

This will display the date in local time. If you want it in UTC Time:

let currentDate = new Date();
let currentYear = currentDate.getFullUTCYear();
let currentMonth = currentDate.getUTCMonth() + 1 // January is Month 0, so we add one
let currentDay = currentDate.getUTCDay();

And extract:

yyyy-mm-dd:

    if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
    }

    if (currentMonth < 10){
        currentMonth = '0' + currentMonth
    }

let newDate = currentYear + "-" + currentMonth + "-" + currentDay;

See it in action:

function showDate() {

  let currentDate = new Date();
  let currentYear = currentDate.getFullYear();
  let currentMonth = currentDate.getMonth() + 1 // January is Month 0, so we add one
  let currentDay = currentDate.getDay();

     if (currentDay < 10){
        currentDay = '0'+ currentDay // Add a 0 before the day if it is less than 10
     }

     if (currentMonth < 10){
        currentMonth = '0' + currentMonth
     }

  let newDate = currentYear + "-" + currentMonth + "-" + currentDay;

  document.getElementById('seeDate').innerHTML = newDate;

}

<button onclick="showDate()">See the date</button>

<div id="seeDate"></div>

You can also you the toLocaleDateString(), toDateString(), toISOString(), or toLocaleString() for easier methods. But I would stick to the ones above because are able to easily change the format in seconds.

I hope this helps!


问:
WindowsError: [Error 5] Access is denied when trying to kill a subprocess (python)
So I have a python script that runs a loop in which it calls a program A through subprocess.Popen waits for its output, then saves the output and then calls it again and so on. (This keeps happening for a number of runs I set as an input)

The thing is that I have a timer so that whenever the program A takes more than a particular  threshold_time, the script kills the process with process.kill() and moves on to the next iteration.

The problem is that even though everything seems to work fine even for 300 runs, sometimes I get this error:

```<code>    File "C:\Python27\lib\subprocess.py", line 1002, in terminate
    _subprocess.TerminateProcess(self._handle, 1)
    WindowsError: [Error 5] Access is denied
</code>```

and then the script dies.

The referred script part:

```<code>timeout = TIME_CONST
for run in runs:
    killed = False
    start = time.clock()
    p = subprocess.Popen("SOME.CMD", cwd=r"some_dir")
    # Monitor process. If it hits threshold, kill it and go to the next run
    while p.poll() is None:
        time.sleep(20)
        secs_passed = time.clock() - start

        ### the following was my initial buggy line ###
        #if secs_passed >= timeout:

        ### corrected line after jedislight's answer ###
        #if the time is over the threshold and process is still running, kill it
        if secs_passed >= timeout and p.poll is None:
            p.kill()
            killed = True
            break
    if killed: continue
</code>```

Do you have any suggestions what the problem might be?

EDIT:
Accepted answer and fixed the code. Thanks @jedislight for your feedback!

答:
You are seperating your p.poll() and your p.kill() by 20 seconds. By then the process could have finished. I would suggest moving the time.sleep(20) call around so that you poll and kill happen in the same time frame, to avoid killing a dead process. Below is an example run in iPython showing a similar error when killing a completed process:

```<code>In [2]: import subprocess

In [3]: p = subprocess.Popen("dir")

In [4]: p.poll()
Out[4]: 0

In [5]: p.kill()
---------------------------------------------------------------------------
WindowsError                              Traceback (most recent call last)

C:\Users\---\<ipython console> in <module>()

C:\Python26\lib\subprocess.pyc in terminate(self)
    947             """Terminates the process
    948             """
--> 949             _subprocess.TerminateProcess(self._handle, 1)
    950
    951         kill = terminate

WindowsError: [Error 5] Access is denied
</code>```

Even if you kill directly after a poll that shows the processes is running it can finish before the next line is executed. I would also suggest adding a try-catch block for this exception and if it occurs poll again to see if the process actually completed.

Body:
So I have a python script that runs a loop in which it calls a program A through subprocess.Popen waits for its output, then saves the output and then calls it again and so on. (This keeps happening for a number of runs I set as an input)

The thing is that I have a timer so that whenever the program A takes more than a particular  threshold_time, the script kills the process with process.kill() and moves on to the next iteration.

The problem is that even though everything seems to work fine even for 300 runs, sometimes I get this error:

    File "C:\Python27\lib\subprocess.py", line 1002, in terminate
    _subprocess.TerminateProcess(self._handle, 1)
    WindowsError: [Error 5] Access is denied

and then the script dies.

The referred script part:

timeout = TIME_CONST
for run in runs:
    killed = False
    start = time.clock()
    p = subprocess.Popen("SOME.CMD", cwd=r"some_dir")
    # Monitor process. If it hits threshold, kill it and go to the next run
    while p.poll() is None:
        time.sleep(20)
        secs_passed = time.clock() - start

        ### the following was my initial buggy line ###
        #if secs_passed >= timeout:

        ### corrected line after jedislight's answer ###
        #if the time is over the threshold and process is still running, kill it
        if secs_passed >= timeout and p.poll is None:
            p.kill()
            killed = True
            break
    if killed: continue

Do you have any suggestions what the problem might be?

EDIT:
Accepted answer and fixed the code. Thanks @jedislight for your feedback!

Body:
You are seperating your p.poll() and your p.kill() by 20 seconds. By then the process could have finished. I would suggest moving the time.sleep(20) call around so that you poll and kill happen in the same time frame, to avoid killing a dead process. Below is an example run in iPython showing a similar error when killing a completed process:

In [2]: import subprocess

In [3]: p = subprocess.Popen("dir")

In [4]: p.poll()
Out[4]: 0

In [5]: p.kill()
---------------------------------------------------------------------------
WindowsError                              Traceback (most recent call last)

C:\Users\---\<ipython console> in <module>()

C:\Python26\lib\subprocess.pyc in terminate(self)
    947             """Terminates the process
    948             """
--> 949             _subprocess.TerminateProcess(self._handle, 1)
    950
    951         kill = terminate

WindowsError: [Error 5] Access is denied

Even if you kill directly after a poll that shows the processes is running it can finish before the next line is executed. I would also suggest adding a try-catch block for this exception and if it occurs poll again to see if the process actually completed.


问:
I am trying to add a modal to my html page but the close button seems to have a problem
I made a modal in my web-page and it shows when I click the but when I click close nothing happens (it doesn't close) any idea?

function voice() {
  $("#myModal").modal('show');
  $('.try').css("opacity", "0.3");

}

function closeModal() {
  $("#myModal").modal('hide');
  $('.try').css("opacity", "1");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
----- Try -----
<div id="myModal" class="modal fade" tabindex="-1" style="opacity:1;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">Try saying something...</h3>
        <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">×</button>

      </div>
      <div class="modal-body">
        <i class="fas fa-microphone"></i>
        <button class="button button5"></button>
      </div>

    </div>
  </div>
</div></code>```

答:
I solved it by changing this

```<code><div id="myModal" class="modal fade" tabindex="-1" style="opacity:1;">
</code>```

to this

```<code><div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">
</code>```

Body:
I made a modal in my web-page and it shows when I click the but when I click close nothing happens (it doesn't close) any idea?

function voice() {
  $("#myModal").modal('show');
  $('.try').css("opacity", "0.3");

}

function closeModal() {
  $("#myModal").modal('hide');
  $('.try').css("opacity", "1");
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

----- Try -----

Try saying something...

        <button type="button" class="close" data-dismiss="modal" onclick="closeModal()">×</button>

        <button class="button button5"></button>

Body:
I solved it by changing this

<div id="myModal" class="modal fade" tabindex="-1" style="opacity:1;">

to this

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">


问:
Google Maps (ReferenceError: google is not defined)
I use google map's API in my website to show couple of locations.
Google Maps is working fine .
But when I want to calculate the distance between to latitude and longitude I got this error ( ReferenceError: google is not defined)

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}
</code>```

home.component.html

```<code><agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">
<!-- ... -->
<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>
<div>
 Distance: {{distance}}
 </div>
 <!-- ... -->
</code>```

Only thing it says: ReferenceError: google is not defined

Does anyone familiar with such problem?

答:
Try

In the index.html,

< script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key={your_key_here}" async defer>

Include googlemaps in types of tsconfig.app.json

Example:

```<code> {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
</code>```

Body:
I use google map's API in my website to show couple of locations.
Google Maps is working fine .
But when I want to calculate the distance between to latitude and longitude I got this error ( ReferenceError: google is not defined)

home.component.ts

import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}

home.component.html

<agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">

<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>

 Distance: {{distance}}

Only thing it says: ReferenceError: google is not defined

Does anyone familiar with such problem?

Body:
Try

In the index.html,

< script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key={your_key_here}" async defer>

Include googlemaps in types of tsconfig.app.json

Example:

 {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}


问:
How to open Windows Terminal with 4 panes?
I want to open 4 equal panes in Windows Terminal using wt.exe from command line. This is the intended result:

I have attempted using split-pane, but without a focus-pane command, it doesn't work.

Is it possible to do so in any other way?

答:
Update on 09/06/2021

We can finally achieve it through command line arguments. Here is a working example:

wt -M -d "./dir-a"; ^
split-pane -V -d "./dir-b"; ^
move-focus left; ^
split-pane -H -d "./dir-c"; ^
move-focus right; ^
split-pane -H -d "./dir-d"
```
<p><strong>Old Answer</strong></p>
<p>I was able to get it working programatically using JScript. Not as beautiful as using <code>wt.exe</code> arguments, but it is the best we can do from a bat file nowadays.</p>
<pre class="lang-js prettyprint-override"><code>@if (@X) == (@Y) @end /*
@cscript //E:JScript //nologo "%~f0" "%*"
@exit /b %errorlevel%
*/

// run windows terminal
var shell = WScript.CreateObject("WScript.Shell");
shell.run("wt.exe");
WScript.Sleep(500);

// ALT+SHIFT+=
shell.SendKeys("%+=");
WScript.Sleep(500);

// ALT+SHIFT+-
shell.SendKeys("%+-");
WScript.Sleep(500);

// focus left pane
shell.SendKeys("%{LEFT}");

// ALT+SHIFT+-
WScript.Sleep(500);
shell.SendKeys("%+-");
</code>```

Body:
Update on 09/06/2021

We can finally achieve it through command line arguments. Here is a working example:

wt -M -d "./dir-a"; ^
split-pane -V -d "./dir-b"; ^
move-focus left; ^
split-pane -H -d "./dir-c"; ^
move-focus right; ^
split-pane -H -d "./dir-d"

Old Answer

I was able to get it working programatically using JScript. Not as beautiful as using wt.exe arguments, but it is the best we can do from a bat file nowadays.

@if (@X) == (@Y) @end /*
@cscript //E:JScript //nologo "%~f0" "%*"
@exit /b %errorlevel%
*/

// run windows terminal
var shell = WScript.CreateObject("WScript.Shell");
shell.run("wt.exe");
WScript.Sleep(500);

// ALT+SHIFT+=
shell.SendKeys("%+=");
WScript.Sleep(500);

// ALT+SHIFT+-
shell.SendKeys("%+-");
WScript.Sleep(500);

// focus left pane
shell.SendKeys("%{LEFT}");

// ALT+SHIFT+-
WScript.Sleep(500);
shell.SendKeys("%+-");


答:
Above component decorator type</p>

```<code>var google: any;
</code>```

Title: Google Maps (ReferenceError: google is not defined)

Body:
Above component decorator type

var google: any;


问:
I can't seem to get the npm module 'upper-case' to work properly
I installed the npm module upper-case as following

```<code>npm install upper-case
</code>```

Thereafter, I executed the following code in node.

```<code>let http = require('http');
let uc = require('upper-case');
http.createServer( (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(uc("Hello World!"));
  res.end();
}).listen(8080);
</code>```

However, I can not get it to work. I get the following response.

```<code>TypeError: uc is not a function
    at Server.http.createServer (/.../foo.js:34:13)
    at Server.emit (events.js:189:13)
    at parserOnIncoming (_http_server.js:676:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
</code>```

Why? What's going on!?

答:
This works (i.e. drop the ".upperCase" from "uc.upperCase"):</p>

```<code>var http = require('http');
var uc = require('uppercase');

http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(uc("Hello World!"));
          res.end();
}).listen(8080);
</code>```

Body:
I installed the npm module upper-case as following

npm install upper-case

Thereafter, I executed the following code in node.

let http = require('http');
let uc = require('upper-case');
http.createServer( (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(uc("Hello World!"));
  res.end();
}).listen(8080);

However, I can not get it to work. I get the following response.

TypeError: uc is not a function
    at Server.http.createServer (/.../foo.js:34:13)
    at Server.emit (events.js:189:13)
    at parserOnIncoming (_http_server.js:676:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)

Why? What's going on!?

Body:
This works (i.e. drop the ".upperCase" from "uc.upperCase"):

var http = require('http');
var uc = require('uppercase');

http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(uc("Hello World!"));
          res.end();
}).listen(8080);


问:
Automatic Slowmode Discord.js
I've been trying to create a system that automatically sets the slowmode in a channel to a certain amount depending on how many messages have been sent. Lua is my primary language, and not Node.js, therefore I'm having quite a bit of trouble as to how I would go about this. If anyone had any suggestions, please let me know.</p>

答:
Two ways to go about it:

Use discord.js's <TextChannel>.setRateLimitPerUser(number)
https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=setRateLimitPerUser

Not sure if this actually does what you want though, the other option is creating a session storage of the text channels msgCount and compare it to time, i found setRateLimitPerUser in the middle of writing the code so didn't finish it, be here's a start:

const { Client, Collection } = require("discord.js");
const client = new Client();

client.slowdown = new Collection();

client.on("message", msg => {
    const id = msg.channel.id;
    const attempt = client.slowdown.get(id);
    //4 messages at most per second
    const ratio = 4;
    //look at last how many seconds
    const timeSpace = 5;

    //TODO: check if channel already has cooldown

    if (attempt) {
        attempt.msgCount++;
        const currentTime = Date.now();
        const timePassed = (currentTime - attempt.time) / 1000;

        if (attempt.msgCount >= ratio && attempt.msgCount / timePassed >= ratio) {
            //setCoolDown
        }

        if (timePassed >= timeSpace) {
            attempt.time = currentTime;
            attempt.msgCount = 0;
        }

    } else {
        client.slowdown.set(id, {
            time: Date.now(),
            msgCount: 1
        });
    }
});
```

Title: Automatic Slowmode Discord.js


问:
how to convert byte* into jpeg file in VC++
how to convert byte*  into jpeg file in VC++

i am capturing Video samples and writing it as bmp files, but i want to write that video samples into jpeg file using MFC support in ATL COM.

答:
From what it appears, you have the image data in a buffer pointed to by a byte object. Note, that the type actually is BYTE (all uppercase). If the data is in JPEG format already why don't you write that data out to a file (with a suitable '.jpg' or '.jpeg' extension) and try loading it with an image editor? Otherwise, you will need to decode that to raw format and encode in the JPEG format.

Or, you need to explain you problem in more detail, preferably with some code.

OwnerDisplayName: BALA

LastEditorDisplayName: BALA

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dirkgently


问:
Rails help model design problem
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

```<code>before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end
</code>```

答:
A simpler way would be to catch the error on the spot.

```<code>rating = rating_score - ratings rescue 0
</code>```

This will instantly catch the ZeroDivisionError and pass the 0 through. (Be careful though. It will also catch and rescue any other error happening inside your rating_score and ratings calls)

Another season, another reason, to love Ruby :)

Title: Rails help model design problem

Body:
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end

Body:
A simpler way would be to catch the error on the spot.

rating = rating_score - ratings rescue 0

This will instantly catch the ZeroDivisionError and pass the 0 through. (Be careful though. It will also catch and rescue any other error happening inside your rating_score and ratings calls)

Another season, another reason, to love Ruby :)


问:
how to find phrases in dictionary from a list of phrases and creating dataframe with phrase found and count. duplicates should be counted
```<code>phrases = ['i am good', 'going to the market', 'eating cookies']

dictionary = {'http://www.firsturl.com': 'i am going to the market and tomorrow will be eating cookies',
             'http://www.secondurl.com': 'tomorrow is my birthday and i shall be',
             'http://www.thirdurl.com': 'i am good and will go to sleep'}
</code>```

if there is at least a match:
  expected output:

```<code>url                             phrasecount    phrase
http://www.firsturl.com         2              going to the market, eating cookies
http://www.thirdurl.com         1              i am good
</code>```

If there is no match from all 3 urls the return just the first occurrence url with zero count and blank phrase
expected output:

```<code>url                            phrasecount    phrase
http://www.firsturl.com        0
</code>```

答:
Setup the initial dataframe df from corresponding dictionary:

```<code>df = pd.DataFrame({'urls': list(dictionary.keys()), 'strings': list(dictionary.values())})
pattern = '|'.join(phrases)
</code>```

Process the dataframe:

```<code>s = df.pop('strings').str.findall(pattern)
df = df.assign(phrasecount=s.str.len(), phrase=s.map(', '.join))
df = df.drop_duplicates(subset='phrasecount') if df['phrasecount'].eq(0).all() else df[df['phrasecount'].ne(0)]
</code>```

Result:

```<code># print(df)

                      urls  phrasecount                               phrase
0  http://www.firsturl.com            2  going to the market, eating cookies
2  http://www.thirdurl.com            1                            i am good
</code>```

Body:
phrases = ['i am good', 'going to the market', 'eating cookies']

dictionary = {'http://www.firsturl.com': 'i am going to the market and tomorrow will be eating cookies',
             'http://www.secondurl.com': 'tomorrow is my birthday and i shall be',
             'http://www.thirdurl.com': 'i am good and will go to sleep'}

if there is at least a match:
  expected output:

url                             phrasecount    phrase
http://www.firsturl.com         2              going to the market, eating cookies
http://www.thirdurl.com         1              i am good

If there is no match from all 3 urls the return just the first occurrence url with zero count and blank phrase
expected output:

url                            phrasecount    phrase
http://www.firsturl.com        0

Body:
Setup the initial dataframe df from corresponding dictionary:

df = pd.DataFrame({'urls': list(dictionary.keys()), 'strings': list(dictionary.values())})
pattern = '|'.join(phrases)

Process the dataframe:

s = df.pop('strings').str.findall(pattern)
df = df.assign(phrasecount=s.str.len(), phrase=s.map(', '.join))
df = df.drop_duplicates(subset='phrasecount') if df['phrasecount'].eq(0).all() else df[df['phrasecount'].ne(0)]

Result:

# print(df)

                      urls  phrasecount                               phrase
0  http://www.firsturl.com            2  going to the market, eating cookies
2  http://www.thirdurl.com            1                            i am good


问:
Can't connect with my frontend with kubectl
With kubernetes, I created an ingress with a service like these :

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: syntaxmap2
spec:
  backend:
    serviceName: testsvc
    servicePort: 3000
</code>```

The service testsvc is already created.

I created a frontend service like these :

```<code>apiVersion: v1
kind: Service
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    app: syntaxmap
    tier: frontend
  ports:
  - protocol: "TCP"
    port: 7000
    targetPort: 7000
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    matchLabels:
      app: syntaxmap
      tier: frontend
      track: stable
  replicas: 1
  template:
    metadata:
      labels:
        app: syntaxmap
        tier: frontend
        track: stable
    spec:
      containers:
      - name: nginx
        image: "gcr.io/google-samples/hello-frontend:1.0"
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]
</code>```

When I do these command :

```<code>kubectl describe ingress syntaxmap2
</code>```

I have an Ip adress than i can put in my browser and I have an answer

But when I do these command :

```<code>kubctl describe service syntaxmapfrontend
</code>```

I have an Ip adress with a port and when I try to connect to it with curl, I have a time out.

How can I connect to my kubernet frontend with curl ?

答:
The service is accessible only from within the k8s cluster. You either need to change the type of address from ClusterIP to NodeIP, or use something like kubectl port-forward or kubefwd.

If you need more detailed advice, you'll need to post the output of those commands, or even better, show us how you created the objects.

Body:
With kubernetes, I created an ingress with a service like these :

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: syntaxmap2
spec:
  backend:
    serviceName: testsvc
    servicePort: 3000

The service testsvc is already created.

I created a frontend service like these :

apiVersion: v1
kind: Service
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    app: syntaxmap
    tier: frontend
  ports:
  - protocol: "TCP"
    port: 7000
    targetPort: 7000
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    matchLabels:
      app: syntaxmap
      tier: frontend
      track: stable
  replicas: 1
  template:
    metadata:
      labels:
        app: syntaxmap
        tier: frontend
        track: stable
    spec:
      containers:
      - name: nginx
        image: "gcr.io/google-samples/hello-frontend:1.0"
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]

When I do these command :

kubectl describe ingress syntaxmap2

I have an Ip adress than i can put in my browser and I have an answer

But when I do these command :

kubctl describe service syntaxmapfrontend

I have an Ip adress with a port and when I try to connect to it with curl, I have a time out.

How can I connect to my kubernet frontend with curl ?


问:
Visual Studio Code retrive UnsupportedClassVersions when run
In Visual Studio Code:

I have OpenJDK 14 correctly configured. When I try to run my project I receive the follow error:
java.lang.UnsupportedClassVersionError: (class file version 56.65535) was compiled with preview features that are unsupported. This version of the Java Runtime only recognizes preview features for class file version 58.65535

This class is a dependency and it is stored in a Nexus Repository, all this project have been compiled with JDK 12. So I try to uninstall OpenJDK 14 to install OpenJDK 12 but If I do this the project can't build because 'Preview features enabled at an invalid source release level 12, preview can be enabled only at source level 14'.

But the same project is correctly build in Eclipse for example.

答:
Can you try running the "Java: clean the Java language server workspace" command?

Or

Updating java extension to the latest version.

As you described, the first time you try to take JRE 14 to run the file which was compiled
with javac 12, then you downgrade to JDK 12 and want to use JRE 12 to run the file. But you get the error of 'Preview features enabled at an invalid source ...'. It seems like a cache causes this. Or did you use some preview features of JDK 14 in your project?


问:
convert WriteableImage to BufferedImage
I need some help concerning Writable- and BufferedImages in Java (11, Javafx):

How do I convert a WritabeImage to a BufferedImage? - WITHOUT using SwingFXUtils.fromFXImage()

It is important for me to find a solution without SwingFXUtils.fromFXImage(). I have already asked google, but the only results I am getting contain SwingFXUtils.fromFXImage(). So I am asking for your expertise.

Could you please help me?

Thanks!

答:
Thanks for your help!

That is how my code looks like (including the 'SwingFXUtils' which I need to avoid):

```<code>static public void createImg(Node NODE, String name) {
        WritableImage SNAPSHOT = NODE.snapshot(new SnapshotParameters(), null);
        File file = new File(Properties.getSettingsPath() + File.separator + name + ".png");
        try {
            ImageIO.write(SwingFXUtils.fromFXImage(SNAPSHOT, null), "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Title: convert WriteableImage to BufferedImage

Body:
Thanks for your help!

That is how my code looks like (including the 'SwingFXUtils' which I need to avoid):

static public void createImg(Node NODE, String name) {
        WritableImage SNAPSHOT = NODE.snapshot(new SnapshotParameters(), null);
        File file = new File(Properties.getSettingsPath() + File.separator + name + ".png");
        try {
            ImageIO.write(SwingFXUtils.fromFXImage(SNAPSHOT, null), "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


问:
Unable to establish Connection on the proceeding request
I have been running my JMeter script with the following setup
Users: 100
Loop Controller: 5
I used Loop Controller on the http request where transactions are needed to iterate.

My question is, there is a particular request which is searching where after 5 successful search the proceeding searches displayed “Customer API. Unable to establish connection”

Please see image below:
1 First Image displays lower load time while second image displays higher load time

答:
It looks like you discovered a bottleneck in your application or at least it is not properly configured for high loads. Almost a minute response time for transfering 600 kilobytes is not something I would expect from a well-behaved application. </p>

<p>The error message you're getting is very specific so I would recommend checking your application logs as the very first step. The remaining steps would be inspecting application and middleware configuration and ensuring that it's properly set up for high performance and it has enough headroom to operate in terms of CPU, RAM, Network, Disk, etc. </p>

Body:
It looks like you discovered a bottleneck in your application or at least it is not properly configured for high loads. Almost a minute response time for transfering 600 kilobytes is not something I would expect from a well-behaved application.

The error message you're getting is very specific so I would recommend checking your application logs as the very first step. The remaining steps would be inspecting application and middleware configuration and ensuring that it's properly set up for high performance and it has enough headroom to operate in terms of CPU, RAM, Network, Disk, etc.


问:
Angular 8+ - do I need to implement the OnInit function in my components if I am not planning to override it?
I'm working on a project with Angular 8.

I noticed that when I generate components with the command line that they come with OnInit.

e.g.

```<code>export class SideDrawerComponent implements OnInit {

    constructor(private sideDrawerService: SideDrawerService) { }

    public ngOnInit(): void { }

    public close() {
        this.sideDrawerService.closeDrawer();
    }

}
</code>```

As I am not going to override the function, do I need it there?

答: No. You can remove it and the OnInit interface. </p>

Body:
I'm working on a project with Angular 8.

I noticed that when I generate components with the command line that they come with OnInit.

e.g.

export class SideDrawerComponent implements OnInit {

    constructor(private sideDrawerService: SideDrawerService) { }

    public ngOnInit(): void { }

    public close() {
        this.sideDrawerService.closeDrawer();
    }

}

As I am not going to override the function, do I need it there?


答:
From the docs:

The hooks give you the opportunity to act on a component or directive
  instance at the appropriate moment, as Angular creates, updates, or
  destroys that instance. If you implement this method in your component
  or directive class, Angular calls it shortly after checking the input
  properties for that component or directive for the first time.

So it isn't mandatory, but will be triggered if you include it.

Also if you so wish to include a lifecycle hook (eg. ngOnInit) then implementing the corresponding interface (OnInit) isn't mandatory. The interface is only there to guide the users for type checks and typos. In theory you could include all the lifecycle hook functions without implementing their interface counterparts.

See here more info.

Title: Angular 8+ - do I need to implement the OnInit function in my components if I am not planning to override it?


问:
Do we nee to login to our account to get an authorization code as first step towards creation of token in docusign?
If URI for getting authorization code is : https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature&client_id=7c2b8d7e-xxxx-xxxx-xxxx-cda8a50dd73f&state=a39fh23hnf23&redirect_uri=http://example.com/callback/
do I need to login to get the authization code.
Is there another way to get token in production environment?
Is there an api available for login in docusign?</p>

答:
Based on your question, I would strongly suggest reading this guide on DocuSign authentication. </p>

<p>As to whether you need to have each and every user login to DocuSign, the answer is no. If you're developing a service integration, you can use the JWT grant flow to interact directly with DocuSign w/o having to authenticate each individual user. </p>

Body:
Based on your question, I would strongly suggest reading this guide on DocuSign authentication.

As to whether you need to have each and every user login to DocuSign, the answer is no. If you're developing a service integration, you can use the JWT grant flow to interact directly with DocuSign w/o having to authenticate each individual user.


问:
How to bind label text placed inside a split Button Content with the selected List box item?
I am trying to create a drop-down like control using WPF split button. I can get drop down working but what I want to achieve next is that if a user select an item from dropdown menu, that text is updated as split Button Content. Also, By default when this control is loaded, first item name is set to split button content.

My preference is to do it in xaml itself.

Here's existing code:

```<code><userControls:BaseUserControl x:Class="UserControls.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:userControls="clr-namespace:MainAssembly.UserControls"
         xmlns:const="clr-namespace:MainAssembly.const"
         xmlns:toolkit="abc/Wpf.Toolkit"
         xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="800">

<userControls:BaseUserControl.Resources>
    <ResourceDictionary>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <toolkit:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
        <toolkit:MultiValueToObjectArrayConverter x:Key="MultiValueToObjectArrayConverter" />
        <toolkit:BoolToInvertedBoolToVisibilityConverter x:Key="BoolToInvertedBoolToVisibilityConverter" />
    </ResourceDictionary>
</userControls:BaseUserControl.Resources>

<xctk:SplitButton Name="TestSplitBtn" ToolBar.OverflowMode="AsNeeded"
                                          Margin="5,1,5,1"
                                          >
    <xctk:SplitButton.DropDownContent>
        <ListBox Name="DropDownMenu" Margin="5,1,5,5"
                                  ItemsSource="{Binding DropDownContentCollection}"
                                  ToolBar.OverflowMode="AsNeeded"
                                  Visibility="{Binding DropDownContentCollection, Converter={StaticResource NullToVisibilityConverter}}"
                                  ToolTip="{x:Static const:const.toolTip}"
                                      MaxWidth="150">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Style="{DynamicResource TransparentButton}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" Command="{Binding DataContext.TestCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}">
                        <Button.Content>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                                <Rectangle Fill="{DynamicResource Icon_Test}" Margin="4,0,5,0" Height="16" Width="16" />
                                <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{} {0}({1})">
                                            <Binding Path="Name" />
                                            <Binding Path="ImageCount" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Style>
                <Style TargetType="{x:Type ListBox}" BasedOn="{StaticResource ListBoxStyle}">
                    <Setter Property="ItemContainerStyle">
                        <Setter.Value>
                            <Style TargetType="ListBoxItem">
                                <Setter Property="AutomationProperties.AutomationId" Value="{Binding Name}"/>
                            </Style>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.Style>
        </ListBox>
    </xctk:SplitButton.DropDownContent>

    <xctk:SplitButton.Content>
        <toolkit:LabelledButton x:Name="TestSeries"
                                                        AutomationProperties.AutomationId="TestBtn"
                                                        CommandParameter="{Binding ViewerState}" Margin="0,1,0,0" Height="56">
            <toolkit:LabelledButton.Content>
                <Rectangle Fill="{DynamicResource Icon_Test}" Margin="0,2,0,-5"/>

            </toolkit:LabelledButton.Content>
            <toolkit:LabelledButton.Style>
                <Style TargetType="{x:Type toolkit:LabelledButton}" BasedOn="{StaticResource {x:Type toolkit:LabelledButton}}">
                    <Setter Property="LabelText" Value="{Binding SelectedImageSeries, Mode=TwoWay}" />
                    <Setter Property="ToolTip" Value="{Binding SelectedImageSeries, Mode=TwoWay}" />
                </Style>
            </toolkit:LabelledButton.Style>
        </toolkit:LabelledButton>
    </xctk:SplitButton.Content>

    <xctk:SplitButton.Style>
        <Style TargetType="{x:Type xctk:SplitButton}" BasedOn="{StaticResource TestSplitButtonStyle}">
            <Setter Property="Visibility" Value="Visible"/>
        </Style>
    </xctk:SplitButton.Style>
</xctk:SplitButton>
</code>```

Also, when I click on the button, It execute the command associated but dropdown menu doesn't get closed.

答:
You also have to bind the ListBox.SelectedItem property to SelectedImageSeries.

It looks like your are using the SplitButton too complicated. I've posted a simplified solution.
Since we are now properly binding the SelectedImageSeries item from the ListBox, there is no need to add a Button to the DataTemplate of the ListBoxItem.

Instead of executing the TestCommand, you can handle the selected item directly in the property setter. I have added a method OnSelectedImageSeriesChanged to the view model for this purpose.

There is also no need to add another button (LabelButton) nested into the SplitButton.Content. You can modify the content layout by assigning a DataTemplate to SplitButton.ContentTemplate and bind a ICommand to the SplitButton.Command property and optionally use SplitButton.CommandParameter.

BindingMode.TwoWay is only required when you send back data to the data source. It's  redundant in every place you have used it: LabelText and ToolTip never send data (they can't). Most of the properties that can send data as they are reflecting user input are binding TwoWay by default e.g., TextBox.Text, ListBox.SelectedItem, ToggleButton.IsChecked etc.

View Model

```<code>class MainViewModel
{
  public ObservableCollection<ImageSeries> DropDownContentCollection { get; }

  private ImageSeries selectedImageSeries;
  public ImageSeries SelectedImageSeries
  {
    get => this.selectedImageSeries;
    set
    {
      this.selectedImageSeries = value;
      OnPropertyChanged();

      // Handle ListBox item selected. Replaces command.
      OnSelectedImageSeriesChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}
</code>```

SplitButton

```<code><xctk:SplitButton Width="100"
                  Content="{Binding SelectedImageSeries}"
                  Command="{Binding HandleButtonPressedCommand}"
                  CommandParameter="{Binding ViewerState}">
  <xctk:SplitButton.ContentTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding}" />
        <Rectangle Fill="{DynamicResource Icon_Test}" Width="20" Height="20" />
      </StackPanel>
    </DataTemplate>
  </xctk:SplitButton.ContentTemplate>
  <xctk:SplitButton.DropDownContent>
    <ListBox ItemsSource="{Binding DropDownContentCollection}" SelectedItem="{Binding SelectedImageSeries}" />
  </xctk:SplitButton.DropDownContent>
</xctk:SplitButton>
</code>```

Body:
I am trying to create a drop-down like control using WPF split button. I can get drop down working but what I want to achieve next is that if a user select an item from dropdown menu, that text is updated as split Button Content. Also, By default when this control is loaded, first item name is set to split button content.

My preference is to do it in xaml itself.

Here's existing code:

<userControls:BaseUserControl x:Class="UserControls.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:userControls="clr-namespace:MainAssembly.UserControls"
         xmlns:const="clr-namespace:MainAssembly.const"
         xmlns:toolkit="abc/Wpf.Toolkit"
         xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="800">

<userControls:BaseUserControl.Resources>
    <ResourceDictionary>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <toolkit:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
        <toolkit:MultiValueToObjectArrayConverter x:Key="MultiValueToObjectArrayConverter" />
        <toolkit:BoolToInvertedBoolToVisibilityConverter x:Key="BoolToInvertedBoolToVisibilityConverter" />
    </ResourceDictionary>
</userControls:BaseUserControl.Resources>

<xctk:SplitButton Name="TestSplitBtn" ToolBar.OverflowMode="AsNeeded"
                                          Margin="5,1,5,1"
                                          >
    <xctk:SplitButton.DropDownContent>
        <ListBox Name="DropDownMenu" Margin="5,1,5,5"
                                  ItemsSource="{Binding DropDownContentCollection}"
                                  ToolBar.OverflowMode="AsNeeded"
                                  Visibility="{Binding DropDownContentCollection, Converter={StaticResource NullToVisibilityConverter}}"
                                  ToolTip="{x:Static const:const.toolTip}"
                                      MaxWidth="150">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Style="{DynamicResource TransparentButton}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" Command="{Binding DataContext.TestCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}">
                        <Button.Content>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                                <Rectangle Fill="{DynamicResource Icon_Test}" Margin="4,0,5,0" Height="16" Width="16" />
                                <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{} {0}({1})">
                                            <Binding Path="Name" />
                                            <Binding Path="ImageCount" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Style>

                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.Style>
        </ListBox>
    </xctk:SplitButton.DropDownContent>

    <xctk:SplitButton.Content>
        <toolkit:LabelledButton x:Name="TestSeries"
                                                        AutomationProperties.AutomationId="TestBtn"
                                                        CommandParameter="{Binding ViewerState}" Margin="0,1,0,0" Height="56">
            <toolkit:LabelledButton.Content>
                <Rectangle Fill="{DynamicResource Icon_Test}" Margin="0,2,0,-5"/>

            </toolkit:LabelledButton.Content>
            <toolkit:LabelledButton.Style>

            </toolkit:LabelledButton.Style>
        </toolkit:LabelledButton>
    </xctk:SplitButton.Content>

    <xctk:SplitButton.Style>

    </xctk:SplitButton.Style>
</xctk:SplitButton>

Also, when I click on the button, It execute the command associated but dropdown menu doesn't get closed.

Body:
You also have to bind the ListBox.SelectedItem property to SelectedImageSeries.

It looks like your are using the SplitButton too complicated. I've posted a simplified solution.
Since we are now properly binding the SelectedImageSeries item from the ListBox, there is no need to add a Button to the DataTemplate of the ListBoxItem.

Instead of executing the TestCommand, you can handle the selected item directly in the property setter. I have added a method OnSelectedImageSeriesChanged to the view model for this purpose.

There is also no need to add another button (LabelButton) nested into the SplitButton.Content. You can modify the content layout by assigning a DataTemplate to SplitButton.ContentTemplate and bind a ICommand to the SplitButton.Command property and optionally use SplitButton.CommandParameter.

BindingMode.TwoWay is only required when you send back data to the data source. It's  redundant in every place you have used it: LabelText and ToolTip never send data (they can't). Most of the properties that can send data as they are reflecting user input are binding TwoWay by default e.g., TextBox.Text, ListBox.SelectedItem, ToggleButton.IsChecked etc.

View Model

class MainViewModel
{
  public ObservableCollection<ImageSeries> DropDownContentCollection { get; }

  private ImageSeries selectedImageSeries;
  public ImageSeries SelectedImageSeries
  {
    get => this.selectedImageSeries;
    set
    {
      this.selectedImageSeries = value;
      OnPropertyChanged();

      // Handle ListBox item selected. Replaces command.
      OnSelectedImageSeriesChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

SplitButton

<xctk:SplitButton Width="100"
                  Content="{Binding SelectedImageSeries}"
                  Command="{Binding HandleButtonPressedCommand}"
                  CommandParameter="{Binding ViewerState}">
  <xctk:SplitButton.ContentTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding}" />
        <Rectangle Fill="{DynamicResource Icon_Test}" Width="20" Height="20" />
      </StackPanel>
    </DataTemplate>
  </xctk:SplitButton.ContentTemplate>
  <xctk:SplitButton.DropDownContent>
    <ListBox ItemsSource="{Binding DropDownContentCollection}" SelectedItem="{Binding SelectedImageSeries}" />
  </xctk:SplitButton.DropDownContent>
</xctk:SplitButton>


问:
NIFI EXECUTESCRIPT Processor failing - No MODULE FOUND
I am trying to import modules into executescript processor in nifi.
As suggested , I. am giving full path into the modules directory.

example:
Module Directory: /var/lib/nifi/Levenshtein --> which contains necessary files for the script.

Furthermore, In the script also I have set the system path pointing to use that module directory
My code Looks something like this

import re
import datetime
import sys
sys.path.append('/var/lib/nifi/Levenshtein')

import Levenshtein
```

When I am running the processor with above code it fails.

ERROR: No Module named Levenshtein in  at line number 3.

答: To sum up what Andy said, this Levensthein module is written in C and cannot be executed by a Java virtual machine, assuming you are running a Jython implementation.</p>

Body:
I am trying to import modules into executescript processor in nifi.
As suggested , I. am giving full path into the modules directory.

example:
Module Directory: /var/lib/nifi/Levenshtein --> which contains necessary files for the script.

Furthermore, In the script also I have set the system path pointing to use that module directory
My code Looks something like this

import re
import datetime
import sys
sys.path.append('/var/lib/nifi/Levenshtein')

import Levenshtein

When I am running the processor with above code it fails.

ERROR: No Module named Levenshtein in  at line number 3.


问:
How can I create a Class file and JAR file without main function?
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here</p>

```<code>public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}
</code>```

答:
The link that you provided tells you how to do it:

Compile your class in the normal way.

Create a JAR file containing your class in the normal way.

Copy the JAR file into the wonza installation's lib as described in the javadoc.

Edit the startup script to add the -Dcom.wowza.wms.logging.LogNotify=... option to JAVA_OPTS ... as described in the javadoc.

The "full-path-to-your-ILogNotify-class" is actually supposed to be the fully qualified class name of your class; it is obvious from the examples.

Edit WowzaMediaServerPro-Service.conf and log4j.properties as described in the javadoc.

Restart the server.

If you put your JAR file in the directory like the instructions tell you to, you won't need to modify the classpath by changing -cp argument.

Your class doesn't need a main method because it is not a free-standing application.  Rather, it is a "plugin" class that gets dynamically loaded and instantiated by the Wowza core as required.  The "-D..." option and the config file change tell the Wonza core which class to try to load.

Body:
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here

public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}


问:
Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
```<code>FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
</code>```

Jenkins ver. 2.73.3
MacOSx

Doing an iOS build and upload to hockeyapp.  The .ipa is created successfully, error seems to happen afterwards, seems like on the hockeyapp upload.  I have an android project that works and uploads to hockeyapp successfully though.

Started getting this today after updating Jenkins and plugins.  Was working before.

Any ideas?

答:
we've been seeing this intermittently on an old Jenkins server and I think we've tracked it down.  It happens when there are background processes left after a job runs and can be easily reproduced with this job script:

```<code>sleep 30 &
exit 0
</code>```

The error Could not initialize class hudson.util.ProcessTree$UnixReflection comes from this static initializer:

```<code>        static {
            try {
                Class<?> clazz = Class.forName("java.lang.UNIXProcess");
                PID_FIELD = clazz.getDeclaredField("pid");
                PID_FIELD.setAccessible(true);

                if (isPreJava8()) {
                    DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class);
                } else {
                    DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class, boolean.class);
                }
                DESTROY_PROCESS.setAccessible(true);
            } catch (ClassNotFoundException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            } catch (NoSuchFieldException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            } catch (NoSuchMethodException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            }
        }
</code>```

The signature of UNIXProcess.destoryProcess changed in Java 8.  Java 9 and forward may have made further changes.  You'll need a JDK that has what Jenkins wants to find in that class.

Body:
FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)

Jenkins ver. 2.73.3
MacOSx

Doing an iOS build and upload to hockeyapp.  The .ipa is created successfully, error seems to happen afterwards, seems like on the hockeyapp upload.  I have an android project that works and uploads to hockeyapp successfully though.

Started getting this today after updating Jenkins and plugins.  Was working before.

Any ideas?

Body:
we've been seeing this intermittently on an old Jenkins server and I think we've tracked it down.  It happens when there are background processes left after a job runs and can be easily reproduced with this job script:

sleep 30 &
exit 0

The error Could not initialize class hudson.util.ProcessTree$UnixReflection comes from this static initializer:

        static {
            try {
                Class<?> clazz = Class.forName("java.lang.UNIXProcess");
                PID_FIELD = clazz.getDeclaredField("pid");
                PID_FIELD.setAccessible(true);

                if (isPreJava8()) {
                    DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class);
                } else {
                    DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class, boolean.class);
                }
                DESTROY_PROCESS.setAccessible(true);
            } catch (ClassNotFoundException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            } catch (NoSuchFieldException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            } catch (NoSuchMethodException e) {
                LinkageError x = new LinkageError();
                x.initCause(e);
                throw x;
            }
        }

The signature of UNIXProcess.destoryProcess changed in Java 8.  Java 9 and forward may have made further changes.  You'll need a JDK that has what Jenkins wants to find in that class.


问:
Symfony Dynamic Form - Get file from embedded form gives NULL
I have a dynamic form which display/hide a FileType field depending on another field value (link).
When i'm trying to get the file in my controller, it always gives me NULL

My UserType:

```<code>    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('familyStatus', ChoiceType::class, [
                'label' => 'Statut de famille',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true,
                'choices' => [
                    'Married' => 'M',
                    'Single' => 'S'
                ]
            ]);

        $formModifier = function (FormInterface $form, $status = null) {
            if ($status === 'M') {
                $form->add('familyInfo', FamilyInfoType::class);
            }
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $user = $event->getData();
                $formModifier($event->getForm(), $user->getFamilyStatus());
            }
        );

        $builder->get('familyStatus')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $status = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $status);
            }
        );

    }
</code>```

My FamilyInfoType:

```<code>    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('partnerName', TextType::class, [
                'label' => 'Nom du partenaire',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true
            ])
            ->add('weddingProof', FileType::class, [
                'label' => 'Acte de mariage',
                'label_attr' => [
                    'class' => 'Upload-label'
                ],
                'attr' => [
                    'class' => 'Upload-input',
                    'maxsize'     =>'4M',
                    'accept'      =>'image/*'
                ],
                'required' => false,
                'mapped' => false
            ]);
    }
</code>```

My UserController:

```<code>    /**
     * @Route("/user", name="add_user", methods={"GET", "POST"})
     * @param Request $request
     */
    public function addUser(Request $request) {
        $response = [];

        $user = new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($user->getFamilyStatus() === 'M') {
                var_dump("ok");

                $document = $form->get('familyInfo')->get('weddingProof')->getData();
                $partnerName = $form->get('familyInfo')->get('partnerName')->getData();

                var_dump($document); // NULL
                var_dump($partnerName); // OK the value is displayed
                die;
            }
        }

        return $this->render("user/registration.html.twig", ['form' => $form->createView()]);
   }
</code>```

It's working with TextType field but not with FileType. What's wrong with my form.

答: The issue is with the mapped => false option to the file type. The form is not setting the uploaded file object in the property of your entity because it’s not mapped.</p>

Body:
I have a dynamic form which display/hide a FileType field depending on another field value (link).
When i'm trying to get the file in my controller, it always gives me NULL

My UserType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('familyStatus', ChoiceType::class, [
                'label' => 'Statut de famille',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true,
                'choices' => [
                    'Married' => 'M',
                    'Single' => 'S'
                ]
            ]);

        $formModifier = function (FormInterface $form, $status = null) {
            if ($status === 'M') {
                $form->add('familyInfo', FamilyInfoType::class);
            }
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $user = $event->getData();
                $formModifier($event->getForm(), $user->getFamilyStatus());
            }
        );

        $builder->get('familyStatus')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $status = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $status);
            }
        );

    }

My FamilyInfoType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('partnerName', TextType::class, [
                'label' => 'Nom du partenaire',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true
            ])
            ->add('weddingProof', FileType::class, [
                'label' => 'Acte de mariage',
                'label_attr' => [
                    'class' => 'Upload-label'
                ],
                'attr' => [
                    'class' => 'Upload-input',
                    'maxsize'     =>'4M',
                    'accept'      =>'image/*'
                ],
                'required' => false,
                'mapped' => false
            ]);
    }

My UserController:

    /**
     * @Route("/user", name="add_user", methods={"GET", "POST"})
     * @param Request $request
     */
    public function addUser(Request $request) {
        $response = [];

        $user = new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($user->getFamilyStatus() === 'M') {
                var_dump("ok");

                $document = $form->get('familyInfo')->get('weddingProof')->getData();
                $partnerName = $form->get('familyInfo')->get('partnerName')->getData();

                var_dump($document); // NULL
                var_dump($partnerName); // OK the value is displayed
                die;
            }
        }

        return $this->render("user/registration.html.twig", ['form' => $form->createView()]);
   }

It's working with TextType field but not with FileType. What's wrong with my form.


问:
Is it possible to have a turn server without configuring realm?
I was trying to host a turn server for my webRTC project. I have my entire server running on a virtual machine static public IP Address. I found this article Turn Server Installation Guide. For configuring the turn server we need to have a domain name that is not available in my case. Is it possible to have a turn server running on my public IP without configuring any domain/realm name?</p>

答: Yes I found it is not necessary to configure the realm.</p>


问:
WebShare API not sharing images on iOS: Angular
I am using the WebShare API to share images natively to different apps via Web. It is working perfectly fine on Android devices and they are sharing the images and the text. However, the same API on Safari in iOS is unable to do so. It is sharing only the text that goes along with the image but the image itself is missing.

This is my code in angular:

share() {
    if (this.windowNavigator.share) {
      this.windowNavigator
        .share({
          files: [this.file],
          title: "Title of the image",
          text: "Text to accompany the image",
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
      console.error("Cannot use Web Share API");
    }
  }
```

Kindly help me proceed

答: File sharing on iOS via the WebShare API is not supported. It is supported only on Android.</p>

Body:
I am using the WebShare API to share images natively to different apps via Web. It is working perfectly fine on Android devices and they are sharing the images and the text. However, the same API on Safari in iOS is unable to do so. It is sharing only the text that goes along with the image but the image itself is missing.

This is my code in angular:

share() {
    if (this.windowNavigator.share) {
      this.windowNavigator
        .share({
          files: [this.file],
          title: "Title of the image",
          text: "Text to accompany the image",
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
      console.error("Cannot use Web Share API");
    }
  }

Kindly help me proceed