问:
mysql: setting a charset and collation on the DB level
I'd like to set charset and collation to the db, such that any new table created with no collation specified will have this collation.

I heard it's possible. Is it?
Is it possible to do it by means of code or only from configuration files?
If it is possible by means of code, how?

Thanks

答:
```<code>[client]
default-character-set=charset_name
</code>```

http://dev.mysql.com/doc/refman/5.0/en/charset-configuration.html

To do with code, I believe you would just have to make sure to set the character set at the beginning of your application loads (which I don't think is the answer you're looking for).

Body:
[client]
default-character-set=charset_name

http://dev.mysql.com/doc/refman/5.0/en/charset-configuration.html

To do with code, I believe you would just have to make sure to set the character set at the beginning of your application loads (which I don't think is the answer you're looking for).


来源: stackexchange

问:
Python Linked lists AttributeError: 'NoneType' object has no attribute 'next'
I'm trying to write a program to delete duplicate values from a linked list

```<code>class Node(object):
def __init__(self, data):
    self.data = data
    self.next = None

class LinkedList(object):
    def __init__(self):
        self.head = None

    def append(self, data):
        node = self.head
        if(node == None):
            self.head = Node(data)
            return
        while(node.next):
            node = node.next
        node.next = Node(data)
        return

def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headnode = headNode.next
    return

list = LinkedList()

list.append(1)
list.append(2)
list.append(3)
list.append(1)

removeDups(list)
</code>```

The error points to the line at "while(lead.next):" with the Arribute Error 'NoneType' object has no attribute 'next'

Am I not able to assign two values to the same listnode? Are headNode and lead pointers?

答:
This should work for you. You need two changes in your removeDups function:</p>

```<code>def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead and lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headNode = headNode.next
    return
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a program to delete duplicate values from a linked list

class Node(object):
def __init__(self, data):
    self.data = data
    self.next = None

class LinkedList(object):
    def __init__(self):
        self.head = None

    def append(self, data):
        node = self.head
        if(node == None):
            self.head = Node(data)
            return
        while(node.next):
            node = node.next
        node.next = Node(data)
        return

def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headnode = headNode.next
    return

list = LinkedList()

list.append(1)
list.append(2)
list.append(3)
list.append(1)

removeDups(list)

The error points to the line at "while(lead.next):" with the Arribute Error 'NoneType' object has no attribute 'next'

Am I not able to assign two values to the same listnode? Are headNode and lead pointers?

Body:
This should work for you. You need two changes in your removeDups function:

def removeDups(ll):
    if(ll.head is None):
        return
    headNode = ll.head
    while(headNode):
        lead = headNode
        while(lead and lead.next):
            if(lead.next.data == headNode.data):
                lead.next = lead.next.next
            lead = lead.next
        headNode = headNode.next
    return


问:
Do not combine generators in Catch2 test case
I would like to use to more than one generator in a Catch2 test case. My problem is, that when there are more than two generators, they are "combined". So if I write something like this:

```<code>TEST_CASE("Test legal moves on empty 2x1 board") {
    Board board(2, 1);

    auto startPos = GENERATE(Position(0, 0), Position(1, 0));
    auto expectedMoves = GENERATE(Position(1, 0), Position(0, 0));
    auto legalMoves = board.getLegalMoves(startPos);
    REQUIRE(legalMoves[0] == expectedMoves);
}
</code>```

This will result in four test cases:
(startPos[0] vs expectedMoves[0], startPos[0] vs expectedMoves[1], startPos[1] vs expectedMoves[0], startPos[1] vs startPos[1]).

I however want only two: (startPos[0] vs expectedMoves[0], startPos[1] vs startPos[1]).

Is there a way to do it in an elegant and readable way? I would like to avoid things like this:

```<code>TEST_CASE("Test legal moves on empty 2x1 board") {
    Board board(2, 1);

    auto dump = GENERATE(vector<Position>{ Position(0, 0), Position(1, 0) },
                         vector<Position>{ Position(1, 0), Position(0, 0) });
    auto expectedMoves = dump[1];
    auto legalMoves = board.getLegalMoves(dump[0]);
    REQUIRE(legalMoves[0] == expectedMoves);
}
</code>```

As maintenance of such monstrosity is cumbersome.

EDIT: I do not really like this solution:
https://github.com/catchorg/Catch2/blob/ce42deb72fab2be85a862f559984580c24cb76c4/projects/SelfTest/UsageTests/Generators.tests.cpp#L199

答:
Instead of using multiple generators you should wrap your input/output test data in some structure that will define both startPos and expectedMove. Then you can use single generator to produce data sets. Your data will be named, so you don't have to reference to it by index. Your TEST_CASE could look like this:

```<code>struct TestData
{
    Position startPos;
    Position expectedMove;
};

TEST_CASE("Test legal moves on empty 2x1 board")
{
    Board board {2, 1};
    auto testData = GENERATE(TestData {{0, 0}, {1, 0}}, TestData {{1, 0}, {0, 0}});
    auto lagalMoves = board.getLegalMoves(testData.startPos);
    REQUIRE(lagalMoves[0] == testData.expectedMove);
}
</code>```

Body:
I would like to use to more than one generator in a Catch2 test case. My problem is, that when there are more than two generators, they are "combined". So if I write something like this:

TEST_CASE("Test legal moves on empty 2x1 board") {
    Board board(2, 1);

    auto startPos = GENERATE(Position(0, 0), Position(1, 0));
    auto expectedMoves = GENERATE(Position(1, 0), Position(0, 0));
    auto legalMoves = board.getLegalMoves(startPos);
    REQUIRE(legalMoves[0] == expectedMoves);
}

This will result in four test cases:
(startPos[0] vs expectedMoves[0], startPos[0] vs expectedMoves[1], startPos[1] vs expectedMoves[0], startPos[1] vs startPos[1]).

I however want only two: (startPos[0] vs expectedMoves[0], startPos[1] vs startPos[1]).

Is there a way to do it in an elegant and readable way? I would like to avoid things like this:

TEST_CASE("Test legal moves on empty 2x1 board") {
    Board board(2, 1);

    auto dump = GENERATE(vector<Position>{ Position(0, 0), Position(1, 0) },
                         vector<Position>{ Position(1, 0), Position(0, 0) });
    auto expectedMoves = dump[1];
    auto legalMoves = board.getLegalMoves(dump[0]);
    REQUIRE(legalMoves[0] == expectedMoves);
}

As maintenance of such monstrosity is cumbersome.

EDIT: I do not really like this solution:
https://github.com/catchorg/Catch2/blob/ce42deb72fab2be85a862f559984580c24cb76c4/projects/SelfTest/UsageTests/Generators.tests.cpp#L199

Body:
Instead of using multiple generators you should wrap your input/output test data in some structure that will define both startPos and expectedMove. Then you can use single generator to produce data sets. Your data will be named, so you don't have to reference to it by index. Your TEST_CASE could look like this:

struct TestData
{
    Position startPos;
    Position expectedMove;
};

TEST_CASE("Test legal moves on empty 2x1 board")
{
    Board board {2, 1};
    auto testData = GENERATE(TestData {{0, 0}, {1, 0}}, TestData {{1, 0}, {0, 0}});
    auto lagalMoves = board.getLegalMoves(testData.startPos);
    REQUIRE(lagalMoves[0] == testData.expectedMove);
}


问:
QString:number with maximum 2 decimal places without trailing zero
I have a division like this:

```<code>number / 1000.0
</code>```

Sometimes it gives answers like 96.0000000001, sometimes the division works as expected.

I want to limit my number to a maximum of two decimal places and without trailing zeros.

If it's 96.5500000001 it should show 96.55.

If it's 96.4000000001 it should show 96.4

It is possible to format a string in this way?

I've checked the documentation and it provides 'f' argument for specifying the number of the decimal places but this way the trailing zeros remain.
This is what I have tried:

```<code>QString::number(number / 1000.0, 'f', 2)
</code>```

But this gives me for 96.4000000001 --> 96.40 instead of 96.4

Any solution? How can I format in this way?

答:
This returns the formatted number always in fixed (not scientific) notation, and is reasonably efficient:</p>

```<code>QString variableFormat(qreal n) { // assumes max precision of 2
    int i = rint(n * 100.0);
    if (i % 100)
        return QString::number(n, 'f', i % 10 ? 2 : 1);
    else
        return QString::number(i / 100);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a division like this:

number / 1000.0

Sometimes it gives answers like 96.0000000001, sometimes the division works as expected.

I want to limit my number to a maximum of two decimal places and without trailing zeros.

If it's 96.5500000001 it should show 96.55.

If it's 96.4000000001 it should show 96.4

It is possible to format a string in this way?

I've checked the documentation and it provides 'f' argument for specifying the number of the decimal places but this way the trailing zeros remain.
This is what I have tried:

QString::number(number / 1000.0, 'f', 2)

But this gives me for 96.4000000001 --> 96.40 instead of 96.4

Any solution? How can I format in this way?

Body:
This returns the formatted number always in fixed (not scientific) notation, and is reasonably efficient:

QString variableFormat(qreal n) { // assumes max precision of 2
    int i = rint(n * 100.0);
    if (i % 100)
        return QString::number(n, 'f', i % 10 ? 2 : 1);
    else
        return QString::number(i / 100);
}


问:
How can I change data returned from observable while the subscription is active?
I'm using Angular Material's table to display a list of employees coming from an observable stream.

```<code><table mat-table [dataSource]="employees$ | async" matSort class="mat-elevation-z8"
(matSortChange)="onMatSortChange($event)" matSortDisableClear>
...
</table>
</code>```

As you can see, I'm implementing my own sort function that is triggered when a user clicks on one of the column headers. Based on this event, I need to sort the elements in the table. Right now I have this:

```<code>onMatSortChange(sort: Sort): void {
    const { active, direction } = sort;
    const compareFn = (a: Employee, b: Employee) => {
      console.log(direction);
      if (direction === 'asc') {
        if (a[active] > b[active]) { return 1; }
        if (a[active] < b[active]) { return -1; }
        return 0;
      } else if (direction === 'desc') {
        if (a[active] < b[active]) { return 1; }
        if (a[active] > b[active]) { return -1; }
        return 0;
      }
    };
    this.employees$ = this.employees$.pipe(map(results => results.sort(compareFn)));
  }
</code>```

Now this appears to work correctly but I don't believe I should be reassigning the observable like this. I have a console log in my compareFn that prints one more time every time I click a column header (every time I click it, I see the output for all the clicks so far).

Is there an rxjs operator I should be using instead to get the desired result?

答:
You're right that you shouldn't reassign the observable reference. To do this, I would express your sorts as an observable Subject that emits a new sort object whenever the button is clicked. You can merge that sort stream into your main employee one. Something like this...

sorts$ = new Subject<Sort>();
employees$ = this.employeeService.get().pipe(
  withLatestFrom(this.sorts$), // or mergeMap() depending on desired behavior
  map(([employees, sort]) => {
    // your sort logic here
    return sortedEmployees;
  })
);

onMatSortChange(sort: Sort): void {
    this.sorts$.next(sort);
}
```

Body:
I'm using Angular Material's table to display a list of employees coming from an observable stream.

...

As you can see, I'm implementing my own sort function that is triggered when a user clicks on one of the column headers. Based on this event, I need to sort the elements in the table. Right now I have this:

onMatSortChange(sort: Sort): void {
    const { active, direction } = sort;
    const compareFn = (a: Employee, b: Employee) => {
      console.log(direction);
      if (direction === 'asc') {
        if (a[active] > b[active]) { return 1; }
        if (a[active] < b[active]) { return -1; }
        return 0;
      } else if (direction === 'desc') {
        if (a[active]  b[active]) { return -1; }
        return 0;
      }
    };
    this.employees$ = this.employees$.pipe(map(results => results.sort(compareFn)));
  }

Now this appears to work correctly but I don't believe I should be reassigning the observable like this. I have a console log in my compareFn that prints one more time every time I click a column header (every time I click it, I see the output for all the clicks so far).

Is there an rxjs operator I should be using instead to get the desired result?


问:
CrudRepository Filter By One to Many Relation
I have two entity Customer and Order:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
  .....
  @OneToMany(mappedBy="customer")
  private Set<Order> orders = new HashSet<Order>();
  .....
}

```

<pre class="lang-java prettyprint-override"><code>@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    ........
    @ManyToOne()
    private Customer;
    ........
}
</code>```

In the CrudRepository I want to find all customers who have no orders.
How can I write the @Query? Or how can I write the method in CrudRepository Interface?

```<code>@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{

  findBy ......

  @Query(".......")
  find.....

}
</code>```

Thanks!

答:
To query data that's not there you must use left join, something like this would do:

@Query("select c from Customer as c left join c.orders as orders where orders is null")
```

Body:
I have two entity Customer and Order:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
  .....
  @OneToMany(mappedBy="customer")
  private Set<Order> orders = new HashSet<Order>();
  .....
}

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    ........
    @ManyToOne()
    private Customer;
    ........
}

In the CrudRepository I want to find all customers who have no orders.
How can I write the @Query? Or how can I write the method in CrudRepository Interface?

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{

  findBy ......

  @Query(".......")
  find.....

}

Thanks!


问:
pivot_root device or resource busy
Produces the following command on Ubuntu 64bit on VMWare:

```<code>mount /dev/sda1 /newroot
cd /newroot
mkdir old-root
pivot_root . old-root
</code>```

I get an error that I do not understand

```<code>pivot_root: device or resource busy
</code>```

Any ideas?

答:
I saw the same error when the new root directory is a plain directory. When the new root is a mount, it will be ok. A bind mount of a directory is ok too. Also need to make sure the root directory permission is 0755, and owned by the root user.

The related answer states that you need to umount /proc first. I do not see the same.

The host ubnutu is 16.04 and it pivots into 18.04. Used unshare -m -p -f /bin/bash, followed by pivot_root . old_root. The -f is necessary to avoid a memory allocation error.

Title: pivot_root device or resource busy

Body:
Produces the following command on Ubuntu 64bit on VMWare:

mount /dev/sda1 /newroot
cd /newroot
mkdir old-root
pivot_root . old-root

I get an error that I do not understand

pivot_root: device or resource busy

Any ideas?


问:
How to configure IP/listeners in Apache Kafka so that external clients can connect to it
I need to use the ip of kafka for my other microservices. but when am deploying by this method theres no external IP moreover when am trying with localhost everything is working fine. so can anyone help me in understanding how to set up the ext IP of lb for the Kafka here to use it in</p>

答:
You just need to configure advertised listeners so that external clients can connect.

To do so, you need to configure advertised.listeners inside server.properties:

```<code>advertised.listeners=PLAINTEXT://your-kafka-host-1:9092,PLAINTEXT://your-kafka-host-1:9093,PLAINTEXT://your-kafka-host-2:9092,...
</code>```

Alternatively, if you are using Docker images, you simply need to export KAFKA_ADVERTISED_LISTENERS.

Body:
You just need to configure advertised listeners so that external clients can connect.

To do so, you need to configure advertised.listeners inside server.properties:

advertised.listeners=PLAINTEXT://your-kafka-host-1:9092,PLAINTEXT://your-kafka-host-1:9093,PLAINTEXT://your-kafka-host-2:9092,...

Alternatively, if you are using Docker images, you simply need to export KAFKA_ADVERTISED_LISTENERS.


问:
In Python, how do I create a list of files based on specified file extensions?
Let's say I have a folder with a bunch of files (with different file extensions). I want to create a list of files from this folder. However, I want to create a list of files with SPECIFIC file extensions.

These file extensions are categorized into groups.

File Extensions: .jpg, .png, .gif, .pdf, .raw, .docx, .pptx, .xlsx, .js, .html, .css

Group "image" contains .jpg, .png, .gif.
Group "adobe" contains .pdf, .raw. (yes, I'm listing '.raw' as an adobe file for this example :P)
Group "microsoft" contains .docx, .pptx, .xlsx.
Group "webdev" contains .js, .html, .css.

I want to be able to add these files types to a list. That list will be generated in a ".txt" file and would contain ALL files with the chosen file extensions.

So if my folder has 5 image files, 10 adobe files, 5 microsoft files, 3 webdev files and I select  the "image" and "microsoft" groups, this application in Python would create a .txt file that contains a list of filenames with file extensions that belong only in the image and microsoft groups.

The text file would have a list like below:

picture1.jpg
picture2.png
picture3.gif
picture4.jpg
picture5.jpg
powerpoint.pptx
powerpoint2.pptx
spreadsheet.xlsx
worddocument.docx
worddocument2.docx

As of right now, my code creates a text file that generates a list of ALL files in a specified folder.
I could use an "if" statement to get specific file extension, but I don't think this achieves the results I want. In this case, I would have to create a function for each Group (i.e. function for the image, adobe, microsoft and webdev groups). I want to be able to combine these groups freely (i.e. image and microsoft files in a list).

Example of an "if" statement:

```<code>for elem in os.listdir(filepath):
    if elem.endswith('.jpg'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    if elem.endswith('.png'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    if elem.endswith('.gif'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    else:
        continue
</code>```

Full code without the "if" statement (generates a .txt file with all filenames from a specified folder):

```<code>import os

def enterFilePath():
    global filepath
    filepath = input("Please enter your file path. ")
    os.chdir(filepath)

enterFilePath()

def enterFileName():
    global name
    global listName
    name = str(input("Name the txt file. "))
    listName = name + ".txt"

enterFileName()

def listGenerator():
    for filename in os.listdir(filepath):
        listItem = filename + ' \n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()

listGenerator()
</code>```

答:
A pointer before getting into the answer - avoid using global in favor of function parameters and return values. It will make debugging significantly less of a headache and make it easier to follow data flow through your program.

nostradamus is correct in his comment, a dict will be the ideal way to solve your problem here. I've also done similar things as your issue before using itertools.chain.from_iterable and pathlib.Path, which I'll be using here.

First, the dict:

```<code>groups = {
    'image': {'jpg', 'png', 'gif'},
    'adobe': {'pdf', 'raw'},
    'microsoft': {'docx', 'pptx', 'xlsx'},
    'webdev': {'js', 'html', 'css'}
}
</code>```

This sets up your extension groups that you mentioned, which you can then access easily with groups['image'], groups['adobe'], etc.

Then, using the Path.glob method, itertools.chain.from_iterable, and a comprehension, you can get your list of desired files in a single statement (or function).

```<code># Set up some variables
target_groups = ['adobe', 'webdev']

# Initialize generator
files = chain.from_iterable(
    # Glob pattern for the current extension
    Path(filepath).glob(f'*.{ext}')
    # Each group in target_groups
    for group in target_groups
    # Each extension in current group
    for ext in groups[group]
)

# Then, just iterate the files
for fpath in files:
    # Do stuff with file here
    print(fpath.name)
</code>```

My test directory has one file of each extension you listed, named a, b, etc for each group. Using the above code, my output is:

```<code>a.pdf
b.raw
a.js
b.html
c.css
</code>```

The way the file list/generator is set up means that the list of files will be sorted by extension-group, then by extension, and then by name. If you want to change what groups are being listed, just add/remove values in the target_groups list above (works with a single option as well).

You'll also want to consider parameterizing your targets, such as through input or script arguments, as well as handling cases where a requested group doesn't exist in the groups dictionary. The code above would probably also be more useful as a function, but I'll leave that implementation up to you :)

Body:
Let's say I have a folder with a bunch of files (with different file extensions). I want to create a list of files from this folder. However, I want to create a list of files with SPECIFIC file extensions.

These file extensions are categorized into groups.

File Extensions: .jpg, .png, .gif, .pdf, .raw, .docx, .pptx, .xlsx, .js, .html, .css

Group "image" contains .jpg, .png, .gif.
Group "adobe" contains .pdf, .raw. (yes, I'm listing '.raw' as an adobe file for this example :P)
Group "microsoft" contains .docx, .pptx, .xlsx.
Group "webdev" contains .js, .html, .css.

I want to be able to add these files types to a list. That list will be generated in a ".txt" file and would contain ALL files with the chosen file extensions.

So if my folder has 5 image files, 10 adobe files, 5 microsoft files, 3 webdev files and I select  the "image" and "microsoft" groups, this application in Python would create a .txt file that contains a list of filenames with file extensions that belong only in the image and microsoft groups.

The text file would have a list like below:

picture1.jpg
picture2.png
picture3.gif
picture4.jpg
picture5.jpg
powerpoint.pptx
powerpoint2.pptx
spreadsheet.xlsx
worddocument.docx
worddocument2.docx

As of right now, my code creates a text file that generates a list of ALL files in a specified folder.
I could use an "if" statement to get specific file extension, but I don't think this achieves the results I want. In this case, I would have to create a function for each Group (i.e. function for the image, adobe, microsoft and webdev groups). I want to be able to combine these groups freely (i.e. image and microsoft files in a list).

Example of an "if" statement:

for elem in os.listdir(filepath):
    if elem.endswith('.jpg'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    if elem.endswith('.png'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    if elem.endswith('.gif'):
        listItem = elem + '\n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()
    else:
        continue

Full code without the "if" statement (generates a .txt file with all filenames from a specified folder):

import os

def enterFilePath():
    global filepath
    filepath = input("Please enter your file path. ")
    os.chdir(filepath)

enterFilePath()

def enterFileName():
    global name
    global listName
    name = str(input("Name the txt file. "))
    listName = name + ".txt"

enterFileName()

def listGenerator():
    for filename in os.listdir(filepath):
        listItem = filename + ' \n'
        listName = filepath + (r"\{}List.txt".format(name))
        writeFile = open(listName, 'a')
        writeFile.write(listItem)
        writeFile.close()

listGenerator()

Body:
A pointer before getting into the answer - avoid using global in favor of function parameters and return values. It will make debugging significantly less of a headache and make it easier to follow data flow through your program.

nostradamus is correct in his comment, a dict will be the ideal way to solve your problem here. I've also done similar things as your issue before using itertools.chain.from_iterable and pathlib.Path, which I'll be using here.

First, the dict:

groups = {
    'image': {'jpg', 'png', 'gif'},
    'adobe': {'pdf', 'raw'},
    'microsoft': {'docx', 'pptx', 'xlsx'},
    'webdev': {'js', 'html', 'css'}
}

This sets up your extension groups that you mentioned, which you can then access easily with groups['image'], groups['adobe'], etc.

Then, using the Path.glob method, itertools.chain.from_iterable, and a comprehension, you can get your list of desired files in a single statement (or function).

# Set up some variables
target_groups = ['adobe', 'webdev']

# Initialize generator
files = chain.from_iterable(
    # Glob pattern for the current extension
    Path(filepath).glob(f'*.{ext}')
    # Each group in target_groups
    for group in target_groups
    # Each extension in current group
    for ext in groups[group]
)

# Then, just iterate the files
for fpath in files:
    # Do stuff with file here
    print(fpath.name)

My test directory has one file of each extension you listed, named a, b, etc for each group. Using the above code, my output is:

a.pdf
b.raw
a.js
b.html
c.css

The way the file list/generator is set up means that the list of files will be sorted by extension-group, then by extension, and then by name. If you want to change what groups are being listed, just add/remove values in the target_groups list above (works with a single option as well).

You'll also want to consider parameterizing your targets, such as through input or script arguments, as well as handling cases where a requested group doesn't exist in the groups dictionary. The code above would probably also be more useful as a function, but I'll leave that implementation up to you :)


问:
how to drop malformed records while loading xls file to spark
While loading csv file, there is an option to drop Malformed records. Can we do the same for XLS file load?
I have tried loading an XLS file (almost 1T size) and it shows this error:

```<code>warning: there was one deprecation warning; re-run with -deprecation for details
sqlContext: org.apache.spark.sql.SQLContext = org.apache.spark.sql.SQLContext@339370e
java.lang.IllegalArgumentException: MALFORMED
  at java.util.zip.ZipCoder.toString(ZipCoder.java:58)
  at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:300)
</code>```

Please, advise. Thank you very much.

答:
I think this is what you are looking for (as done in Java for CSV):

```<code>spark.read().format("csv").option("sep", ",")
                          .option("header", true)
                          .option("mode", "DROPMALFORMED")
                          .schema(schema)
                          .load(filePath);
</code>```

Here, we the mode will take care of malformed records and drop them when encountered.
Similarly, header is set to true which will not consider it as value and separator is defined as comma for CSV file format.

spark is the spark session to be created before the above snippet.

Body:
While loading csv file, there is an option to drop Malformed records. Can we do the same for XLS file load?
I have tried loading an XLS file (almost 1T size) and it shows this error:

warning: there was one deprecation warning; re-run with -deprecation for details
sqlContext: org.apache.spark.sql.SQLContext = org.apache.spark.sql.SQLContext@339370e
java.lang.IllegalArgumentException: MALFORMED
  at java.util.zip.ZipCoder.toString(ZipCoder.java:58)
  at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:300)

Please, advise. Thank you very much.

Body:
I think this is what you are looking for (as done in Java for CSV):

spark.read().format("csv").option("sep", ",")
                          .option("header", true)
                          .option("mode", "DROPMALFORMED")
                          .schema(schema)
                          .load(filePath);

Here, we the mode will take care of malformed records and drop them when encountered.
Similarly, header is set to true which will not consider it as value and separator is defined as comma for CSV file format.

spark is the spark session to be created before the above snippet.


问:
In wordpress Can I add a new Category using PHP in my theme
So basically I am writing a new wordpress theme, Usually i add a new category in wordpress using the admin panel by filling in some info: "name" and the "slug".

I want to do this in my theme by overriding the funtions.php file

For example creating a new category named :  New category , with the slug new_category .
Is it possible ?

And of course, I know that this idea doesn't exactly follow some theme programming guidelines such as envato guideline or the Wordpress.org publishers guideline. And yes the best thing would be to make a plugin for this. But here I am talking about a practical point of view, So is it possible? could you just point me up in the right direction (maybe a link to some doc or so?).

答:
Thanks to @Coder comments I wrote this code that works like a charm for me :

```<code>$mycat_name = 'New category'; //The name of category that I want to add
$mycat_slug = 'new-category'; //The slug (no spaces, lower-cases)
$mycat = $wpdb->get_results( "SELECT t.*, tt.* FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE tt.taxonomy = 'category' AND t.name = '" . $mycat_name . "'");
$checking = sizeof($mycat) ;

//found out that size is 0 if there the category doesn't exist
if ($checking === 0){
$category = array('cat_name'=>$mycat_name, 'category_nicename'=>$mycat_slug);
wp_insert_category($category);
}
</code>```

So this works and you an just add it anywhere (maybe index.php) , also this wil require you to add the following function that I got from wordpress taxonomy file

```<code>  function wp_insert_category( $catarr, $wp_error = false ) {
    $cat_defaults = array(
        'cat_ID'               => 0,
        'taxonomy'             => 'category',
        'cat_name'             => '',
        'category_description' => '',
        'category_nicename'    => '',
        'category_parent'      => '',
    );
    $catarr       = wp_parse_args( $catarr, $cat_defaults );

    if ( trim( $catarr['cat_name'] ) == '' ) {
        if ( ! $wp_error ) {
            return 0;
        } else {
            return new WP_Error( 'cat_name', __( 'You did not enter a category name.' ) );
        }
    }

    $catarr['cat_ID'] = (int) $catarr['cat_ID'];

    // Are we updating or creating?
    $update = ! empty( $catarr['cat_ID'] );

    $name        = $catarr['cat_name'];
    $description = $catarr['category_description'];
    $slug        = $catarr['category_nicename'];
    $parent      = (int) $catarr['category_parent'];
    if ( $parent < 0 ) {
        $parent = 0;
    }

    if ( empty( $parent )
        || ! term_exists( $parent, $catarr['taxonomy'] )
        || ( $catarr['cat_ID'] && term_is_ancestor_of( $catarr['cat_ID'], $parent, $catarr['taxonomy'] ) ) ) {
        $parent = 0;
    }

    $args = compact( 'name', 'slug', 'parent', 'description' );

    if ( $update ) {
        $catarr['cat_ID'] = wp_update_term( $catarr['cat_ID'], $catarr['taxonomy'], $args );
    } else {
        $catarr['cat_ID'] = wp_insert_term( $catarr['cat_name'], $catarr['taxonomy'], $args );
    }

    if ( is_wp_error( $catarr['cat_ID'] ) ) {
        if ( $wp_error ) {
            return $catarr['cat_ID'];
        } else {
            return 0;
        }
    }
    return $catarr['cat_ID']['term_id'];
    }
</code>```

Works for me, a Quick and dirty way to push gategories in your thee directly.

From a practical point (this is good) but still a bad idea with regards to wordpress publishers guidelines where this code must at least be in a plugin.

Body:
Thanks to @Coder comments I wrote this code that works like a charm for me :

$mycat_name = 'New category'; //The name of category that I want to add
$mycat_slug = 'new-category'; //The slug (no spaces, lower-cases)
$mycat = $wpdb->get_results( "SELECT t.*, tt.* FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
WHERE tt.taxonomy = 'category' AND t.name = '" . $mycat_name . "'");
$checking = sizeof($mycat) ;

//found out that size is 0 if there the category doesn't exist
if ($checking === 0){
$category = array('cat_name'=>$mycat_name, 'category_nicename'=>$mycat_slug);
wp_insert_category($category);
}

So this works and you an just add it anywhere (maybe index.php) , also this wil require you to add the following function that I got from wordpress taxonomy file

  function wp_insert_category( $catarr, $wp_error = false ) {
    $cat_defaults = array(
        'cat_ID'               => 0,
        'taxonomy'             => 'category',
        'cat_name'             => '',
        'category_description' => '',
        'category_nicename'    => '',
        'category_parent'      => '',
    );
    $catarr       = wp_parse_args( $catarr, $cat_defaults );

    if ( trim( $catarr['cat_name'] ) == '' ) {
        if ( ! $wp_error ) {
            return 0;
        } else {
            return new WP_Error( 'cat_name', __( 'You did not enter a category name.' ) );
        }
    }

    $catarr['cat_ID'] = (int) $catarr['cat_ID'];

    // Are we updating or creating?
    $update = ! empty( $catarr['cat_ID'] );

    $name        = $catarr['cat_name'];
    $description = $catarr['category_description'];
    $slug        = $catarr['category_nicename'];
    $parent      = (int) $catarr['category_parent'];
    if ( $parent < 0 ) {
        $parent = 0;
    }

    if ( empty( $parent )
        || ! term_exists( $parent, $catarr['taxonomy'] )
        || ( $catarr['cat_ID'] && term_is_ancestor_of( $catarr['cat_ID'], $parent, $catarr['taxonomy'] ) ) ) {
        $parent = 0;
    }

    $args = compact( 'name', 'slug', 'parent', 'description' );

    if ( $update ) {
        $catarr['cat_ID'] = wp_update_term( $catarr['cat_ID'], $catarr['taxonomy'], $args );
    } else {
        $catarr['cat_ID'] = wp_insert_term( $catarr['cat_name'], $catarr['taxonomy'], $args );
    }

    if ( is_wp_error( $catarr['cat_ID'] ) ) {
        if ( $wp_error ) {
            return $catarr['cat_ID'];
        } else {
            return 0;
        }
    }
    return $catarr['cat_ID']['term_id'];
    }

Works for me, a Quick and dirty way to push gategories in your thee directly.

From a practical point (this is good) but still a bad idea with regards to wordpress publishers guidelines where this code must at least be in a plugin.


问:
Detect if <audio> `pause` event fired by user interaction or buffer underrun?
When playing a live audio stream, like web radio, through <audio> or Audio(), the pause event can fire in (at least) three ways:

user clicks on the pause button (with <audio controls>)

user clicks the browsers global audio controls

iOS: Control Center

Android: browser's notification drawer (at least Chrome, Opera, Firefox)

Desktop: Media Session API controls, but uninitialized, without explicit setActionHandler (might be hidden behind a flag as of now)

a buffer underrun caused by various network conditions

Is it possible to distinguish between 1/2 and 3?

Ideally, there would be an event property like isTrusted, which I am missing

I have tried to guess, looking esp. at readyState and networkState, but both are very inconclusive, especially across browsers (e.g. the interpretation/semantics of HAVE_FUTURE_DATA vs HAVE_ENOUGH_DATA)

I have shied away from making a "decaying state machine", juggling other events. A buffer underrun is often preceded by stalled events, and sometimes followed by ended events. A cross-browser implementation seems crazy complex and the danger of false positives very high.

Am I out of luck until Media Session lands everywhere?

Note: this question looks like a solution, but unfortunately isn't -- browsers handle live streams' "ends" differently and inconsistently.

答:
The waiting event should fit your needs.

You can try this demo while you simulate bad network with the dropdown in Chrome's Network tab (e.g: Slow 3G)

const video = document.getElementById('mwe_player_0');
video.onwaiting = function() { console.log('onwaiting'); };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="mwe_player_0" controls="" preload="none" style="width:800px;height:450px"><source src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm" type="video/webm; codecs="vp8, vorbis""></video></code>```

Note that this demo works with HTMLAudioElement as well (because it inherits HTMLMediaElement). The video demo is just easier to test.

Body:
The waiting event should fit your needs.

You can try this demo while you simulate bad network with the dropdown in Chrome's Network tab (e.g: Slow 3G)

const video = document.getElementById('mwe_player_0');
video.onwaiting = function() { console.log('onwaiting'); };

<video id="mwe_player_0" controls="" preload="none" style="width:800px;height:450px"><source src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm" type="video/webm; codecs=&quot;vp8, vorbis&quot;"></video>

Note that this demo works with HTMLAudioElement as well (because it inherits HTMLMediaElement). The video demo is just easier to test.


问:
Calling Powershell from MATLAB does not move to next line in MATLAB
I have a command that calls powershell using !powershell . it works fine but, the first command will execute a publishing of data action from an external program and does not proceed to next line of code in MATLAB until there is a subscriber to the published data. the problem is that the next line of code is the one that subscribes to the published data so it just runs for ever waiting for the data. any ideas how to make the code continue? I have tried the continue statement but since I have called powershell, it stays there and MATLAB commands do not get executed. Also, I have tried to run the commands backwards, so subscriber first and publisher after but get same issue. Any ideas? </p>

```<code>pubPath = 'powershell -inputformat none cd path' ;
subPath = 'powershell -inputformat none cd path2';

[status_one,publish] = system(pubPath);
[status_two,subscribe] = system(subPath);
</code>```

答:
You need to start the job in the background, such that PowerShell returns immediately before the job finishes. Note that it is PowerShell that waits for the job to finish, not MATLAB.

End the PowerShell command with an ampersand (&) to run it in the background:

```<code>[status_one,publish] = system('powershell -inputformat none cd path &');
</code>```

Body:
I have a command that calls powershell using !powershell . it works fine but, the first command will execute a publishing of data action from an external program and does not proceed to next line of code in MATLAB until there is a subscriber to the published data. the problem is that the next line of code is the one that subscribes to the published data so it just runs for ever waiting for the data. any ideas how to make the code continue? I have tried the continue statement but since I have called powershell, it stays there and MATLAB commands do not get executed. Also, I have tried to run the commands backwards, so subscriber first and publisher after but get same issue. Any ideas?

pubPath = 'powershell -inputformat none cd path' ;
subPath = 'powershell -inputformat none cd path2';

[status_one,publish] = system(pubPath);
[status_two,subscribe] = system(subPath);

Body:
You need to start the job in the background, such that PowerShell returns immediately before the job finishes. Note that it is PowerShell that waits for the job to finish, not MATLAB.

End the PowerShell command with an ampersand (&) to run it in the background:

[status_one,publish] = system('powershell -inputformat none cd path &');


问:
Can I use the R package lubridate to parse dates if my month, day, and year are in separate columns?
I am new at using R, but I am trying to learn how to use it to make my data analyses more reproducible. I have my dates entered in three columns for the drop off date and three columns for the pickup date (one for month, one for day, and one for year). I need to be able to get R to recognize it as a date, so I can calculate the time in field as a fraction of a year (days/365). I installed the lubridate package and tried using the mdy() function, but it gave me the following error message:

```<code>Error: Column `drop_off_date` must be length 150 (the number of rows) or one, not 450
In addition: Warning message:
All formats failed to parse. No formats found.
</code>```

I also tried using backticks, but that did not work either. I think it may be because of how my dates are set up in different columns, but I am not sure. This is the section of code I used for that:

```<code>mutate(drop_off_date = mdy(dropoff_month, dropoff_day, dropoff_year),
         pickup_date = mdy(pickup_month, pickup_day, pickup_year),
</code>```

Does anyone have any suggestions for a different function or what I could fix to use this function?

答:
The lubridate functions take a single vector of strings. My first comment suggested paste0 could work too, but not directly (see the code below), so you need to include a separator (such as paste's default " " space).

library(lubridate)
### wrong
mdy(10, 13, 2018)
# Warning: All formats failed to parse. No formats found.
# [1] NA NA NA

### some fixed
mdy(paste(10, 13, 2018))
# [1] "2018-10-13"

library(dplyr)
data.frame(y=c(2018,2019), m=c(10,9), d=c(30,1)) %>%
  mutate(date = mdy(paste(m, d, y)))
#      y  m  d       date
# 1 2018 10 30 2018-10-30
# 2 2019  9  1 2019-09-01
```

Body:
I am new at using R, but I am trying to learn how to use it to make my data analyses more reproducible. I have my dates entered in three columns for the drop off date and three columns for the pickup date (one for month, one for day, and one for year). I need to be able to get R to recognize it as a date, so I can calculate the time in field as a fraction of a year (days/365). I installed the lubridate package and tried using the mdy() function, but it gave me the following error message:

Error: Column `drop_off_date` must be length 150 (the number of rows) or one, not 450
In addition: Warning message:
All formats failed to parse. No formats found.

I also tried using backticks, but that did not work either. I think it may be because of how my dates are set up in different columns, but I am not sure. This is the section of code I used for that:

mutate(drop_off_date = mdy(dropoff_month, dropoff_day, dropoff_year),
         pickup_date = mdy(pickup_month, pickup_day, pickup_year),

Does anyone have any suggestions for a different function or what I could fix to use this function?


问:
Call a function argument stored in a list
I need to test a suite of argument conditions in order to find the best model (using the drc package). That is, I'd like to store function arguments in a list and then call them into the drm() function. The drc package has a function (mselect()) to do this, but it has been known to fail for unknown reasons (https://www.reddit.com/r/Rlanguage/comments/a1bu44/any_idea_what_im_doing_wrong_with_the_mselect/).

Example Data

```<code>library(drc) # This also loads in the S.alba data
data(S.alba)

head(S.alba)
  Dose  Herbicide DryMatter
1    0 Glyphosate       4.7
2    0 Glyphosate       4.6
3    0 Glyphosate       4.1
4    0 Glyphosate       4.4
5    0 Glyphosate       3.2
6    0 Glyphosate       3.0
</code>```

Failed Attempt

```<code># List of function arguments to be assessed e.g. drm(...fct = W1.4(fixed = c(NA, 0.1, NA, NA)
model_list <- list(curve = c(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))

# Failed function, attempting to return a list of results
model_select <- function(data, mlist){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = mlist)
    metric = AIC(model)
    return(metric)
}
model_select(data = S.alba, mlist = model_list)
</code>```

Error in drm(DryMatter ~ Dose, Herbicide, data = ., fct = mlist) :
    First entry in list to 'fct' NOT a function

Semi-Working Attempt

```<code>model_select_2 <- function(data){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = W1.4(fixed = c(NA, 0.1, NA, NA)))
    metric = AIC(model)
    return(metric)
}
model_select_2(data = S.alba)

model_select_2(data = S.alba)
[1] 106.9226
</code>```

Desired Output

```<code>model_select(data = S.alba, mlist = model_list)
[1] W1.4-106.9226
[2] LL.4-99.54702
</code>```

答:
Part of the problem is how you are creating model_list. You want to combine those values with list() rather than c(). The latter tried to combine them into the same object.

The next thing you can do is sapply over the list of curves to get the result for each input. A working example would be

```<code>model_list <- list(curve = list(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))
model_select <- function(data, mlist){
   sapply(mlist$curve, function(curve){
      model <- drm(DryMatter ~ Dose, Herbicide, data = data , fct = curve)
      metric = AIC(model)
   })
}
model_select(data = S.alba, mlist = model_list)
# [1] 106.92259  99.54702
</code>```

Body:
I need to test a suite of argument conditions in order to find the best model (using the drc package). That is, I'd like to store function arguments in a list and then call them into the drm() function. The drc package has a function (mselect()) to do this, but it has been known to fail for unknown reasons (https://www.reddit.com/r/Rlanguage/comments/a1bu44/any_idea_what_im_doing_wrong_with_the_mselect/).

Example Data

library(drc) # This also loads in the S.alba data
data(S.alba)

head(S.alba)
  Dose  Herbicide DryMatter
1    0 Glyphosate       4.7
2    0 Glyphosate       4.6
3    0 Glyphosate       4.1
4    0 Glyphosate       4.4
5    0 Glyphosate       3.2
6    0 Glyphosate       3.0

Failed Attempt

# List of function arguments to be assessed e.g. drm(...fct = W1.4(fixed = c(NA, 0.1, NA, NA)
model_list <- list(curve = c(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))

# Failed function, attempting to return a list of results
model_select <- function(data, mlist){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = mlist)
    metric = AIC(model)
    return(metric)
}
model_select(data = S.alba, mlist = model_list)

Error in drm(DryMatter ~ Dose, Herbicide, data = ., fct = mlist) :
    First entry in list to 'fct' NOT a function

Semi-Working Attempt

model_select_2 <- function(data){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = W1.4(fixed = c(NA, 0.1, NA, NA)))
    metric = AIC(model)
    return(metric)
}
model_select_2(data = S.alba)

model_select_2(data = S.alba)
[1] 106.9226

Desired Output

model_select(data = S.alba, mlist = model_list)
[1] W1.4-106.9226
[2] LL.4-99.54702

Body:
Part of the problem is how you are creating model_list. You want to combine those values with list() rather than c(). The latter tried to combine them into the same object.

The next thing you can do is sapply over the list of curves to get the result for each input. A working example would be

model_list <- list(curve = list(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))
model_select <- function(data, mlist){
   sapply(mlist$curve, function(curve){
      model <- drm(DryMatter ~ Dose, Herbicide, data = data , fct = curve)
      metric = AIC(model)
   })
}
model_select(data = S.alba, mlist = model_list)
# [1] 106.92259  99.54702


问:
React Router navigation issue in Firefox after reloading URL from address bar
I have a navigation issue in a SPA with React 16.12 and React Router 4.3.1 which only happens in the Firefox browser.

For example, starting from the URL /recommendedProducts I navigate to the URL /forms. If I reload the /forms page by pressing enter in the address bar, and immediately I press the browser back button, the URL changes to /recommendedProducts but it doesn't refresh. Investigating and comparing the behavior between Firefox and Chrome I noticed that the popstate event is not triggered in Firefox.

Here are the routes:

```<code><Switch>
    <Route path="/recommendedProducts" component={RecommendedProducts} />
...
    <Route path="/forms" component={Forms} />
</Switch>
</code>```

If, instead of reloading the /forms page this way, I press F5 all is OK, the browser back button works as expected.

Why Firefox doesn't trigger the popstate event and how can inform React Router to refresh the page?

EDIT:
I just find out this React Router issue, this is exactly the problem:
https://github.com/ReactTraining/react-router/issues/837

答:
It seems that the problem has to do with the Firefox cache. As indicated in https://github.com/ReactTraining/react-router/issues/837 defining the unload event handler disables it.

Here the official docs:
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching

Previously I tried also to use the pageshow and pagehide events by refreshing the page from there but they are not always triggered.

Body:
I have a navigation issue in a SPA with React 16.12 and React Router 4.3.1 which only happens in the Firefox browser.

For example, starting from the URL /recommendedProducts I navigate to the URL /forms. If I reload the /forms page by pressing enter in the address bar, and immediately I press the browser back button, the URL changes to /recommendedProducts but it doesn't refresh. Investigating and comparing the behavior between Firefox and Chrome I noticed that the popstate event is not triggered in Firefox.

Here are the routes:

<Switch>
    <Route path="/recommendedProducts" component={RecommendedProducts} />
...
    <Route path="/forms" component={Forms} />
</Switch>

If, instead of reloading the /forms page this way, I press F5 all is OK, the browser back button works as expected.

Why Firefox doesn't trigger the popstate event and how can inform React Router to refresh the page?

EDIT:
I just find out this React Router issue, this is exactly the problem:
https://github.com/ReactTraining/react-router/issues/837


问:
sqlite.create returning null in Angular
Below are my imports in my database.service.ts.

```<code>import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { SQLitePorter } from '@ionic-native/sqlite-porter/ngx';
import { HttpClient } from '@angular/common/http';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
import { BehaviorSubject, Observable } from 'rxjs';
</code>```

Below is the constructor I am using to try to build the database.

```<code>  constructor(private plt: Platform, private sqlitePorter: SQLitePorter, private sqlite: SQLite, private http: HttpClient) {
    this.plt.ready().then(() => {
      const conn = this.sqlite.create({
        name: 'emotions.db',
        location: 'default'
      });
      if (conn == null) throw Error('Failed to create database connection');
      conn.then(() => {
        console.log('Done');
      })
    });
  }
</code>```

This is run when the app begins, and throws the statement I told it to because the conn == null in this case.

I am unsure why this is occurring, as there are no build errors when doing 'ionic serve'.

答:
This is the wrong way to get a response, just try the way of ionic Documentation,</p>

```<code>this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) => {
    console.log(db);
  })
  .catch(e => console.log(e));
</code>```

Title: sqlite.create returning null in Angular

Body:
Below are my imports in my database.service.ts.

import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { SQLitePorter } from '@ionic-native/sqlite-porter/ngx';
import { HttpClient } from '@angular/common/http';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
import { BehaviorSubject, Observable } from 'rxjs';

Below is the constructor I am using to try to build the database.

  constructor(private plt: Platform, private sqlitePorter: SQLitePorter, private sqlite: SQLite, private http: HttpClient) {
    this.plt.ready().then(() => {
      const conn = this.sqlite.create({
        name: 'emotions.db',
        location: 'default'
      });
      if (conn == null) throw Error('Failed to create database connection');
      conn.then(() => {
        console.log('Done');
      })
    });
  }

This is run when the app begins, and throws the statement I told it to because the conn == null in this case.

I am unsure why this is occurring, as there are no build errors when doing 'ionic serve'.

Body:
This is the wrong way to get a response, just try the way of ionic Documentation,

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


问:
The following code is giving me an error: 'list' object has no attribute 'split'
I am trying to decipher a message from a text file by getting the mode of each column and is giving me an attribute error:

'list' object has no attribute 'split'

I know that list has no split, only strings have split.

```<code>file1=open("input.txt","r")
for row_ele in file1.readlines().split("\n"):
    c=0
    for ele_in_row in row_ele:
           #c=row_ele.count(ele_in_row):
            if c<row_ele.count(ele_in_row):
                c=row_ele.count(ele_in_row)
                mode_ele=ele_in_row
    print(mode_ele)
file1.close()
</code>```

答:
The error is telling you the problem: you are trying to call split() on a list, but list has no function called split(). I think you want to take a string and split it into a list of lines separated by '\n' which you could do if you had a string because str has a function named split(). readlines() already does this, so you can just remove the call to split() entirely:

```<code>for row_ele in file1.readlines():
</code>```

Body:
I am trying to decipher a message from a text file by getting the mode of each column and is giving me an attribute error:

'list' object has no attribute 'split'

I know that list has no split, only strings have split.

file1=open("input.txt","r")
for row_ele in file1.readlines().split("\n"):
    c=0
    for ele_in_row in row_ele:
           #c=row_ele.count(ele_in_row):
            if c<row_ele.count(ele_in_row):
                c=row_ele.count(ele_in_row)
                mode_ele=ele_in_row
    print(mode_ele)
file1.close()

Body:
The error is telling you the problem: you are trying to call split() on a list, but list has no function called split(). I think you want to take a string and split it into a list of lines separated by '\n' which you could do if you had a string because str has a function named split(). readlines() already does this, so you can just remove the call to split() entirely:

for row_ele in file1.readlines():


问:
Why do I have to return Unit.INSTANCE in a void kotlin function, when called from Java, and not NULL?
When having a function, for example:

```<code>fun doSomething(action:() -> Unit) {
   action.invoke()
}
</code>```

if I call this from Java the code needs to be:

```<code>doSomething(() -> {
   //do something
   return Unit.INSTANCE
})
</code>```

I have seen code instead using

```<code>doSomething(() -> {
   //do something
   return null
})
</code>```

Does it affect sending null instead of Unit.INSTANCE? Do Kotlin perform more things by validating that UNIT instance is returned instead?

答:
I think most of the time it will not really matter whether null or Unit.INSTANCE is used. However as there is at least 1 case where such a null is not desirable, you should probably always use Unit.INSTANCE then.

One such made-up example where not returning Unit.INSTANCE will cause a problem is the following:

```<code>fun doSomething(action:() -> Unit) {
   action.invoke() logReturnTime("after action invocation")
}
infix fun Unit.logReturnTime(msg : String) { TODO("logging return time $msg") }
</code>```

If you would call this and return null you would get an IllegalArgumentException, whereas the code would run without problem if you use Unit.INSTANCE.

That having said, I don't believe this is a good example, but it clearly shows, if anyone operates on that Unit, then it could fail, so you probably better always use Unit.INSTANCE and you are safe, regardless on what the receiver does with your function.

Body:
When having a function, for example:

fun doSomething(action:() -> Unit) {
   action.invoke()
}

if I call this from Java the code needs to be:

doSomething(() -> {
   //do something
   return Unit.INSTANCE
})

I have seen code instead using

doSomething(() -> {
   //do something
   return null
})

Does it affect sending null instead of Unit.INSTANCE? Do Kotlin perform more things by validating that UNIT instance is returned instead?

Body:
I think most of the time it will not really matter whether null or Unit.INSTANCE is used. However as there is at least 1 case where such a null is not desirable, you should probably always use Unit.INSTANCE then.

One such made-up example where not returning Unit.INSTANCE will cause a problem is the following:

fun doSomething(action:() -> Unit) {
   action.invoke() logReturnTime("after action invocation")
}
infix fun Unit.logReturnTime(msg : String) { TODO("logging return time $msg") }

If you would call this and return null you would get an IllegalArgumentException, whereas the code would run without problem if you use Unit.INSTANCE.

That having said, I don't believe this is a good example, but it clearly shows, if anyone operates on that Unit, then it could fail, so you probably better always use Unit.INSTANCE and you are safe, regardless on what the receiver does with your function.


问:
How to parse HTTP requests
I am making a http request to instagram using http.Get , I was wondering if there was a faster way to check if there is a certain line of text, e.g. I request only part of the html.

tdlr: How do I only get part of the http request.

Code currently works but I would like it faster.

resp, err := http.Get(fmt.Sprintf("https://www.instagram.com/%s", line))
        if err != nil {
            log.Fatalln(err)
        }
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatalln(err)
        }
        // IF RES HERE. ( after bodystring := string(body)
        bodystring := string(body)
        res1 := strings.Contains(bodystring, "
Sorry, this page isn't available.
")
        if res1 == true {
```

答:
For a task such as this, checking if content was found, it's faster and more reliable to check the HTTP status code of the Response.</p>

```<code>resp, err := http.Get(fmt.Sprintf("https://www.instagram.com/%s", line))
if err != nil {
  log.Fatalln(err)
}
if resp.StatusCode == 404 {
  // page was not found
}
</code>```

Title: How to parse HTTP requests

Body:
For a task such as this, checking if content was found, it's faster and more reliable to check the HTTP status code of the Response.

resp, err := http.Get(fmt.Sprintf("https://www.instagram.com/%s", line))
if err != nil {
  log.Fatalln(err)
}
if resp.StatusCode == 404 {
  // page was not found
}


问:
React custom hook not picking up new value
I'm still trying to wrap my head around how React Hooks work. In Building this custom Hook, I noticed a peculiar behavior:

```<code>const useCustomHook = () => {
  const [value, setValue] = useState('hello');

  useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }, []);

  const print = () => console.log('print value: ', value); // shows updated value when called directly but original value when scrolling

  return [setValue, print];
};
</code>```

The peculiar behavior is what print outputs to the console. When calling print directly, the value reflects the correct updated value. But when scrolling, print always outputs the original value to the console.

Example usage:

App.js

```<code>let counter = 0;

const App = () => {
  const [setValue, print] = useCustomHook();

  return (
    <div style={{ margin: '50px auto 10000px' }}>
      <button onClick={() => setValue(counter++)}>Increment</button>{' '}
      <button onClick={print}>Print</button>
    </div>
  );
};
</code>```

Steps:

Click Increment

Click Print -> console: print value: 0

Scroll -> console: print value: hello

Notice is step 3, the value is still hello. How can I get the proper value to be printed when scrolling?

答:
You need to remove the dependencies from useEffect.

```<code>useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }); // remove the empty array
</code>```

If you set it to [], then it will be executed only once.

If you remove it, it will be executed on every update.

Ideally, you want to re-evaluate the code in useEffect only when value changes.
You could then add print to the array of dependencies.

```<code>const useCustomHook = () => {
  const [value, setValue] = useState(-1);

  // useCallback will re-create the function only if 'value' changes
  const print = useCallback(() => {
      console.log('print value: ', value);
  }, [value]);

  // useEffect will be re-evaluated if 'print' changes
  useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }, [print]);

  return [setValue, print];
};
</code>```

Body:
I'm still trying to wrap my head around how React Hooks work. In Building this custom Hook, I noticed a peculiar behavior:

const useCustomHook = () => {
  const [value, setValue] = useState('hello');

  useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }, []);

  const print = () => console.log('print value: ', value); // shows updated value when called directly but original value when scrolling

  return [setValue, print];
};

The peculiar behavior is what print outputs to the console. When calling print directly, the value reflects the correct updated value. But when scrolling, print always outputs the original value to the console.

Example usage:

App.js

let counter = 0;

const App = () => {
  const [setValue, print] = useCustomHook();

  return (

      <button onClick={() => setValue(counter++)}>Increment</button>{' '}
      <button onClick={print}>Print</button>

  );
};

Steps:

Click Increment

Click Print -> console: print value: 0

Scroll -> console: print value: hello

Notice is step 3, the value is still hello. How can I get the proper value to be printed when scrolling?

Body:
You need to remove the dependencies from useEffect.

useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }); // remove the empty array

If you set it to [], then it will be executed only once.

If you remove it, it will be executed on every update.

Ideally, you want to re-evaluate the code in useEffect only when value changes.
You could then add print to the array of dependencies.

const useCustomHook = () => {
  const [value, setValue] = useState(-1);

  // useCallback will re-create the function only if 'value' changes
  const print = useCallback(() => {
      console.log('print value: ', value);
  }, [value]);

  // useEffect will be re-evaluated if 'print' changes
  useEffect(() => {
    window.addEventListener('scroll', print, false);
    return () => window.removeEventListener('scroll', print, false);
  }, [print]);

  return [setValue, print];
};


问:
What's wrong with my JS code for a command prompt?
This was working earlier, and then stopped. No idea why. It should function like this: enter a command into the textbox that is matched with an if statement, and execute the command. The form keeps refreshing after you press enter, so I don't think the "event.preventDefault();" at the end of my JS code is working.

HTML

```<code><form id="command-form" autocomplete="off">
    <img src="img/tint.png" alt="tint-img" id="tint-img" class="CMP">
    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">
    <img id="x-icon" src="img/x-icon.png" alt="x-icon" class="goto-command-console bottom-left-navigation-item" onclick="toggleCMP();">
    <input type="submit" style="display: none;" onclick="checkCommand();">
</form>
</code>```

JavaScript

```<code>function checkCommand() {
    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
    event.preventDefault();
}
</code>```

Edits

A nice gentleman in the comments solved the problem, go check out his answer below. However, my method works too. In an earlier function, I did this:

```<code>function playMusic(url-to-mp3) {
    new Audio(url-to-mp3).play();
}
</code>```

I wasn't even thinking about the dashes in the function object. Both methods work great, and thank you for your help. Sorry for wasting your time.

答:
<input type="submit" style="display: none;" onclick="checkCommand();"> will submit the form on enter as its type is submit even you set to display: none;.

Changing its type to a button will solve your problem but you have to click the button to make it work or you have to handle the enter key (return key ) event to make call to the checkCommand(event)

```<code><input type="button" onclick="checkCommand();">
</code>```

The answer by @max is also a good one as it handles the event, but you have to understand a lot how that function is getting called with the event.

Body:
This was working earlier, and then stopped. No idea why. It should function like this: enter a command into the textbox that is matched with an if statement, and execute the command. The form keeps refreshing after you press enter, so I don't think the "event.preventDefault();" at the end of my JS code is working.

HTML

<form id="command-form" autocomplete="off">

    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">

    <input type="submit" style="display: none;" onclick="checkCommand();">
</form>

JavaScript

function checkCommand() {
    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
    event.preventDefault();
}

Edits

A nice gentleman in the comments solved the problem, go check out his answer below. However, my method works too. In an earlier function, I did this:

function playMusic(url-to-mp3) {
    new Audio(url-to-mp3).play();
}

I wasn't even thinking about the dashes in the function object. Both methods work great, and thank you for your help. Sorry for wasting your time.

Body:
<input type="submit" style="display: none;" onclick="checkCommand();"> will submit the form on enter as its type is submit even you set to display: none;.

Changing its type to a button will solve your problem but you have to click the button to make it work or you have to handle the enter key (return key ) event to make call to the checkCommand(event)

<input type="button" onclick="checkCommand();">

The answer by @max is also a good one as it handles the event, but you have to understand a lot how that function is getting called with the event.


问:
How to run the akka grpc java example
Ok, following the prerequisites and instructions to use Java 8 the project creation works.

sbt new akka/akka-grpc-quickstart-java.g8

Then continuing with the guide

./gradlew compileJava works as well.

but then ./gradlew --info runServer fails with the folling errors/issues:

```<code>Task ':runServer' is not up-to-date because:
Task has not declared any outputs.
</code>```

and

```<code>Error: Main method not found in class com.example.helloworld.GreeterServer, please define the main method as:
   public static void main(String[] args)

</code>```

ORIGINAL POST:

I am having trouble getting the Akka-GRPC example to run.
I tried following this guide here but when I download the sample project it seems incomplete.

Thats the tree command output:

```<code>.
├── build.sbt
├── project
│   ├── build.properties
│   └── plugins.sbt
├── sbt
├── sbt.bat
└── sbt-dist
    ├── bin
    │   ├── sbt
    │   ├── sbt.bat
    │   ├── sbt-launch.jar
    │   └── sbt-launch-lib.bash
    └── conf
        ├── sbtconfig.txt
        └── sbtopts

4 directories, 11 files
</code>```

There are no source files or gradlew oder pom.xml in the project structure.

Next I cloned the repository of that example from GitHub and followed the instructions in readme, mainly the command sbt new akka/akka-grpc-quickstart-java.g8.

```<code>$ sbt new akka/akka-grpc-quickstart-java.g8
[info] Loading settings for project akka-grpc-quickstart-java-g8-build from paradox.sbt,giter8.sbt ...
[info] Loading project definition from /home/johannes/IdeaProjects/akka-grpc-quickstart-java.g8/project
error: error while loading String, class file '/modules/java.base/java/lang/String.class' is broken
(class java.lang.NullPointerException/null)
[error] java.io.IOError: java.lang.RuntimeException: /packages cannot be represented as URI
...//had to remove stacktrace was too long for this post
[error]     at xsbt.boot.Boot.main(Boot.scala)
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? [error] java.io.IOError: java.lang.RuntimeException: /packages cannot be represented as URI
[error] Use 'last' for the full log.
</code>```

then I went into the project/sources folder ./src/main/g8/ where the source files are located and tried to follow the instructions from the guide from in there.
That also did not work because of some properties errors:

Before that I had to set another gradle version (6.1.1, was 4.5.1) in ./gradle/wrapper/gradle-wrapper.properties to make it compatible with Java 13.

```<code>$ ./gradlew compileJava

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'g8'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:$akka_grpc_version$.
     Searched in the following locations:
       - file:/home/johannes/.m2/repository/gradle/plugin/com/lightbend/akka/grpc/akka-grpc-gradle-plugin/$akka_grpc_version$/akka-grpc-gradle-plugin-$akka_grpc_version$.pom
       - https://plugins.gradle.org/m2/gradle/plugin/com/lightbend/akka/grpc/akka-grpc-gradle-plugin/$akka_grpc_version$/akka-grpc-gradle-plugin-$akka_grpc_version$.pom
     Required by:
         project :

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
</code>```

Trying to at least temporarily get this to work i hardcoded the properties into the build.gradle file:

```<code>     //classpath 'gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:$akka_grpc_version$'
     classpath 'gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:0.7.3'
</code>```

But that also only got me so far:

```<code>$ ./gradlew compileJava

FAILURE: Build failed with an exception.

* Where:
Build file '/home/johannes/IdeaProjects/akka-grpc-quickstart-java.g8/src/main/g8/build.gradle' line: 20

* What went wrong:
A problem occurred evaluating root project 'g8'.
> Failed to apply plugin [id 'com.google.protobuf']
   > Could not create an instance of type com.google.protobuf.gradle.ProtobufSourceDirectorySet.
      > 'void org.gradle.api.internal.file.DefaultSourceDirectorySet.<init>(java.lang.String, java.lang.String, org.gradle.api.internal.file.FileResolver, org.gradle.api.internal.file.collections.DirectoryFileTreeFactory)'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
</code>```

Again could not include whole stacktrace because of character limit.

What am I missing?
Which approach should I pursue further?

答:
EDIT: Meanwhile, the pull request was accepted and the main repo (https://github.com/akka/akka-grpc-quickstart-java.g8) is up-to-date.

I downloaded the project using sbt new ..., but there was an error within the pom.xml (fixed version: https://github.com/olitazl/akka-grpc-quickstart-java.g8)

The problem of the example project are missing public modifier inside the GreeterServer class.

Therefore, you have to add public to the GreeterServer class and the method main within.

```<code>    public class GreeterServer ...
    public static void main(...)
</code>```

If you recreate your project from my repo, the problem is fixed there as well.

Title: How to run the akka grpc java example

Body:
Ok, following the prerequisites and instructions to use Java 8 the project creation works.

sbt new akka/akka-grpc-quickstart-java.g8

Then continuing with the guide

./gradlew compileJava works as well.

but then ./gradlew --info runServer fails with the folling errors/issues:

Task ':runServer' is not up-to-date because:
Task has not declared any outputs.

and

Error: Main method not found in class com.example.helloworld.GreeterServer, please define the main method as:
   public static void main(String[] args)

ORIGINAL POST:

I am having trouble getting the Akka-GRPC example to run.
I tried following this guide here but when I download the sample project it seems incomplete.

Thats the tree command output:

.
├── build.sbt
├── project
│   ├── build.properties
│   └── plugins.sbt
├── sbt
├── sbt.bat
└── sbt-dist
    ├── bin
    │   ├── sbt
    │   ├── sbt.bat
    │   ├── sbt-launch.jar
    │   └── sbt-launch-lib.bash
    └── conf
        ├── sbtconfig.txt
        └── sbtopts

4 directories, 11 files

There are no source files or gradlew oder pom.xml in the project structure.

Next I cloned the repository of that example from GitHub and followed the instructions in readme, mainly the command sbt new akka/akka-grpc-quickstart-java.g8.

$ sbt new akka/akka-grpc-quickstart-java.g8
[info] Loading settings for project akka-grpc-quickstart-java-g8-build from paradox.sbt,giter8.sbt ...
[info] Loading project definition from /home/johannes/IdeaProjects/akka-grpc-quickstart-java.g8/project
error: error while loading String, class file '/modules/java.base/java/lang/String.class' is broken
(class java.lang.NullPointerException/null)
[error] java.io.IOError: java.lang.RuntimeException: /packages cannot be represented as URI
...//had to remove stacktrace was too long for this post
[error]     at xsbt.boot.Boot.main(Boot.scala)
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? [error] java.io.IOError: java.lang.RuntimeException: /packages cannot be represented as URI
[error] Use 'last' for the full log.

then I went into the project/sources folder ./src/main/g8/ where the source files are located and tried to follow the instructions from the guide from in there.
That also did not work because of some properties errors:

Before that I had to set another gradle version (6.1.1, was 4.5.1) in ./gradle/wrapper/gradle-wrapper.properties to make it compatible with Java 13.

$ ./gradlew compileJava

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'g8'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:$akka_grpc_version$.
     Searched in the following locations:
       - file:/home/johannes/.m2/repository/gradle/plugin/com/lightbend/akka/grpc/akka-grpc-gradle-plugin/$akka_grpc_version$/akka-grpc-gradle-plugin-$akka_grpc_version$.pom
       - https://plugins.gradle.org/m2/gradle/plugin/com/lightbend/akka/grpc/akka-grpc-gradle-plugin/$akka_grpc_version$/akka-grpc-gradle-plugin-$akka_grpc_version$.pom
     Required by:
         project :

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

Trying to at least temporarily get this to work i hardcoded the properties into the build.gradle file:

     //classpath 'gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:$akka_grpc_version$'
     classpath 'gradle.plugin.com.lightbend.akka.grpc:akka-grpc-gradle-plugin:0.7.3'

But that also only got me so far:

$ ./gradlew compileJava

FAILURE: Build failed with an exception.

* Where:
Build file '/home/johannes/IdeaProjects/akka-grpc-quickstart-java.g8/src/main/g8/build.gradle' line: 20

* What went wrong:
A problem occurred evaluating root project 'g8'.
> Failed to apply plugin [id 'com.google.protobuf']
   > Could not create an instance of type com.google.protobuf.gradle.ProtobufSourceDirectorySet.
      > 'void org.gradle.api.internal.file.DefaultSourceDirectorySet.<init>(java.lang.String, java.lang.String, org.gradle.api.internal.file.FileResolver, org.gradle.api.internal.file.collections.DirectoryFileTreeFactory)'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

Again could not include whole stacktrace because of character limit.

What am I missing?
Which approach should I pursue further?

Body:
EDIT: Meanwhile, the pull request was accepted and the main repo (https://github.com/akka/akka-grpc-quickstart-java.g8) is up-to-date.

I downloaded the project using sbt new ..., but there was an error within the pom.xml (fixed version: https://github.com/olitazl/akka-grpc-quickstart-java.g8)

The problem of the example project are missing public modifier inside the GreeterServer class.

Therefore, you have to add public to the GreeterServer class and the method main within.

    public class GreeterServer ...
    public static void main(...)

If you recreate your project from my repo, the problem is fixed there as well.


问:
Pass args for solve_ivp (new SciPy ODE API)
For solving simple ODEs using SciPy, I used to use the odeint function, with form:

```<code>scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)[source]
</code>```

where a simple function to be integrated could include additional arguments of the form:

```<code>def dy_dt(t, y, arg1, arg2):
    # processing code here
</code>```

In SciPy 1.0, it seems the ode and odeint funcs have been replaced by a newer solve_ivp method.

```<code>scipy.integrate.solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False, **options)
</code>```

However, this doesn't seem to offer an args parameter, nor any indication in the documentation as to implementing the passing of args.

Therefore, I wonder if arg passing is possible with the new API, or is this a feature that has yet to be added? (It would seem an oversight to me if this features has been intentionally removed?)

Reference:
https://docs.scipy.org/doc/scipy/reference/integrate.html

答:
According to Javier-Acuna's ultra-brief, ultra-useful answer, the feature that you (as well as I) desire has recently been added. This was announced on Github by none other than the great Warren Weckesser (See his Github, StackOverflow)  himself.
Anyway, jokes aside the docstring of solve_ivp has an example using it in for the `Lotka-Volterra equations

solve_ivp(
      fun,
      t_span,
      y0,
      method='RK45',
      t_eval=None,
      dense_output=False,
      events=None,
      vectorized=False,
      args=None,
      **options,
  )

So, just include args as a tuple. In your case

```<code>args = (arg1, arg2)
</code>```

Please don't use my answer unless your scipy version >= 1.4 .
There is no args parameter in solve_ivp for versions below it. I have personally experienced my answer failing for version 1.2.1.

The implementation by zahabaz would probably still work fine in case your scipy version < 1.4

Body:
For solving simple ODEs using SciPy, I used to use the odeint function, with form:

scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)[source]

where a simple function to be integrated could include additional arguments of the form:

def dy_dt(t, y, arg1, arg2):
    # processing code here

In SciPy 1.0, it seems the ode and odeint funcs have been replaced by a newer solve_ivp method.

scipy.integrate.solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False, **options)

However, this doesn't seem to offer an args parameter, nor any indication in the documentation as to implementing the passing of args.

Therefore, I wonder if arg passing is possible with the new API, or is this a feature that has yet to be added? (It would seem an oversight to me if this features has been intentionally removed?)

Reference:
https://docs.scipy.org/doc/scipy/reference/integrate.html

Body:
According to Javier-Acuna's ultra-brief, ultra-useful answer, the feature that you (as well as I) desire has recently been added. This was announced on Github by none other than the great Warren Weckesser (See his Github, StackOverflow)  himself.
Anyway, jokes aside the docstring of solve_ivp has an example using it in for the `Lotka-Volterra equations

solve_ivp(
      fun,
      t_span,
      y0,
      method='RK45',
      t_eval=None,
      dense_output=False,
      events=None,
      vectorized=False,
      args=None,
      **options,
  )

So, just include args as a tuple. In your case

args = (arg1, arg2)

Please don't use my answer unless your scipy version >= 1.4 .
There is no args parameter in solve_ivp for versions below it. I have personally experienced my answer failing for version 1.2.1.

The implementation by zahabaz would probably still work fine in case your scipy version < 1.4


问:
Missing logs in IntelliJ
This is an awful question, I know, but already for 15 minutes can't find where to see logs in IntelliJ, where should I press?
Here is a screenshot

答:
Bottom line of your window:

4: Run

That should pop up automatically if you run your application.

Title: Missing logs in IntelliJ


问:
Difference between training a Neural net inside if __name__ == '__main__' and without it
I would be grateful if someone could explain the difference between this code -

```<code>models = (encoder, decoder)
data = (x_test, y_test)

# VAE loss = mse_loss or xent_loss + kl_loss
reconstruction_loss = mse(inputs, outputs)
reconstruction_loss *= original_dim
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')

# train the autoencoder
vae.fit([x_train,y_train_1hot],
    epochs=epochs,
    batch_size=batch_size,
    validation_data=([x_test,y_test], None))
</code>```

and this one -

```<code>if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    help_ = "Load h5 model trained weights"
    parser.add_argument("-w", "--weights", help=help_)
    help_ = "Use mse loss instead of binary cross entropy (default)"
    parser.add_argument("-m",
                        "--mse",
                        help=help_, action='store_true')
    args = parser.parse_args(args=[])
    models = (encoder, decoder)
    data = (x_test, y_test)

    # VAE loss = mse_loss or xent_loss + kl_loss
    if args.mse:
        reconstruction_loss = mse(inputs, outputs)
    else:
        reconstruction_loss = binary_crossentropy(inputs,
                                                  outputs)

    reconstruction_loss *= original_dim
    kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
    kl_loss = K.sum(kl_loss, axis=-1)
    kl_loss *= -0.5
    vae_loss = K.mean(reconstruction_loss + kl_loss)
    vae.add_loss(vae_loss)
    vae.compile(optimizer='adam')

    #if args.weights:
        #vae.load_weights(args.weights)
    #else:
        # train the autoencoder
    vae.fit([x_train,y_train_1hot],
        epochs=epochs,
        batch_size=batch_size,
        validation_data=([x_test,y_test_1hot], None))
        #vae.save_weights('vae_mlp_mnist.h5')
</code>```

To my understanding both of them are the same, and I don't save the weights, and have commented the loading weights code, the validation loss for both comes out to be different, even though the reconstructions look the same. I do not understand why.

答:
There should be no difference if you run the second snippet with python <yourmodule> --mse (otherwise, your second snippet defaults to binary crossentropy, while your first snippet always uses mse).

Apart from that, the if __name__ == '__main__' guard only changes the script's behavior such that included code is only executed when the module (file) is run. I.e., when importing your module, the first snippet would be executed, the second won't.

Body:
I would be grateful if someone could explain the difference between this code -

models = (encoder, decoder)
data = (x_test, y_test)

# VAE loss = mse_loss or xent_loss + kl_loss
reconstruction_loss = mse(inputs, outputs)
reconstruction_loss *= original_dim
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = K.sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = K.mean(reconstruction_loss + kl_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')

# train the autoencoder
vae.fit([x_train,y_train_1hot],
    epochs=epochs,
    batch_size=batch_size,
    validation_data=([x_test,y_test], None))

and this one -

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    help_ = "Load h5 model trained weights"
    parser.add_argument("-w", "--weights", help=help_)
    help_ = "Use mse loss instead of binary cross entropy (default)"
    parser.add_argument("-m",
                        "--mse",
                        help=help_, action='store_true')
    args = parser.parse_args(args=[])
    models = (encoder, decoder)
    data = (x_test, y_test)

    # VAE loss = mse_loss or xent_loss + kl_loss
    if args.mse:
        reconstruction_loss = mse(inputs, outputs)
    else:
        reconstruction_loss = binary_crossentropy(inputs,
                                                  outputs)

    reconstruction_loss *= original_dim
    kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
    kl_loss = K.sum(kl_loss, axis=-1)
    kl_loss *= -0.5
    vae_loss = K.mean(reconstruction_loss + kl_loss)
    vae.add_loss(vae_loss)
    vae.compile(optimizer='adam')

    #if args.weights:
        #vae.load_weights(args.weights)
    #else:
        # train the autoencoder
    vae.fit([x_train,y_train_1hot],
        epochs=epochs,
        batch_size=batch_size,
        validation_data=([x_test,y_test_1hot], None))
        #vae.save_weights('vae_mlp_mnist.h5')

To my understanding both of them are the same, and I don't save the weights, and have commented the loading weights code, the validation loss for both comes out to be different, even though the reconstructions look the same. I do not understand why.


答:
If you have used the readline() it became file1 = {'line1', 'line2', ...}. You can only use

```<code>for row_ele in file1.readlines():
</code>```

or

```<code>for row_ele in file1.split('\n'):
</code>```

Title: The following code is giving me an error: 'list' object has no attribute 'split'

Body:
If you have used the readline() it became file1 = {'line1', 'line2', ...}. You can only use

for row_ele in file1.readlines():

or

for row_ele in file1.split('\n'):