问:
Retrieve the List property count of realm for tableview Swift
I am using Realm 3 and Swift 4 and still new to Realm and Swift. Need a guidance here :)

Given this realm model

```<code>class Person: Object, Mappable {
    let dog = List<Dog>()

    required convenience init?(map: Map) {
        self.init()
    }
}
</code>```

How can I get the dog count of each person?

What i want to achieve is there are multiple sections on my table view and for each person there will be dog list for the respective person.

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let owner = realm.objects(Person.self)
    return owner.dog.count // This is not working. What should I change it to ?
}
</code>```

I have been searching through the web but couldn't find any guide on such problem.

Any help given is highly appreciated. Thanks!

答:
I would probably rename the var dog to var dogs to indicate it may contain more than one dog.

Here's a straightforward solution that prints the owners name and dog count.

```<code>do {
    let realm = try Realm()
    let people = realm.objects(Person.self)

    for person in people {
        let name = person.personName
        print(name)

        let dogs = person.dogs
        print(dogs.count)
    }

} catch let error as NSError {
    print(error.localizedDescription)
}
</code>```

A Realm List has Array functionality so it can be iterated over, count is available and can also be filtered.

And the code in your question

```<code>let owners = realm.objects(Person.self)
</code>```

will assign all Person objects in Realm to the owners var (an array of Person) so it's not one person it would be all of them which is why it doesn't have a .dog property.

You will need to establish which person is supposed to be in each section of the tableView, query Realm for that person and then return person.dogs.count.

The code to determine how you determine which person goes in which section isn't shown in the original question but lets assume you want person 0 in section 0 (there may be an ordering issue so this is just conceptual)

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let owners = realm.objects(Person.self).sorted('name')
    let thisOwner = owners[section]
    let dogCount = thisOwner.dogs.count
    return dogCount
}
</code>```

Body:
I am using Realm 3 and Swift 4 and still new to Realm and Swift. Need a guidance here :)

Given this realm model

class Person: Object, Mappable {
    let dog = List<Dog>()

    required convenience init?(map: Map) {
        self.init()
    }
}

How can I get the dog count of each person?

What i want to achieve is there are multiple sections on my table view and for each person there will be dog list for the respective person.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let owner = realm.objects(Person.self)
    return owner.dog.count // This is not working. What should I change it to ?
}

I have been searching through the web but couldn't find any guide on such problem.

Any help given is highly appreciated. Thanks!

Body:
I would probably rename the var dog to var dogs to indicate it may contain more than one dog.

Here's a straightforward solution that prints the owners name and dog count.

do {
    let realm = try Realm()
    let people = realm.objects(Person.self)

    for person in people {
        let name = person.personName
        print(name)

        let dogs = person.dogs
        print(dogs.count)
    }

} catch let error as NSError {
    print(error.localizedDescription)
}

A Realm List has Array functionality so it can be iterated over, count is available and can also be filtered.

And the code in your question

let owners = realm.objects(Person.self)

will assign all Person objects in Realm to the owners var (an array of Person) so it's not one person it would be all of them which is why it doesn't have a .dog property.

You will need to establish which person is supposed to be in each section of the tableView, query Realm for that person and then return person.dogs.count.

The code to determine how you determine which person goes in which section isn't shown in the original question but lets assume you want person 0 in section 0 (there may be an ordering issue so this is just conceptual)

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let owners = realm.objects(Person.self).sorted('name')
    let thisOwner = owners[section]
    let dogCount = thisOwner.dogs.count
    return dogCount
}


来源: stackexchange

问:
EditText, clear focus on touch outside
My layout contains ListView, SurfaceView and EditText. When I click on the EditText, it receives focus and the on-screen keyboard pops up. When I click somewhere outside of the EditText, it still has the focus (it shouldn't).
I guess I could set up OnTouchListener's on the other views in layout and manually clear the EditText's focus. But seems too hackish...

I also have the same situation in the other layout - list view with different types of items, some of which have EditText's inside. They act just like I wrote above.

The task is to make EditText lose focus when user touches something outside of it.

I've seen similar questions here, but haven't found any solution...

答:
For Me Below things Worked -

1.Adding android:clickable="true" and android:focusableInTouchMode="true" to the parentLayout of EditTexti.e android.support.design.widget.TextInputLayout

```<code><android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusableInTouchMode="true">
<EditText
    android:id="@+id/employeeID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    android:hint="Employee ID"
    tools:layout_editor_absoluteX="-62dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_marginTop="42dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="36dp"
    android:layout_marginEnd="36dp" />
    </android.support.design.widget.TextInputLayout>
</code>```

2.Overriding dispatchTouchEvent in Activity class and inserting hideKeyboard() function

```<code>@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null && view instanceof EditText) {
                Rect r = new Rect();
                view.getGlobalVisibleRect(r);
                int rawX = (int)ev.getRawX();
                int rawY = (int)ev.getRawY();
                if (!r.contains(rawX, rawY)) {
                    view.clearFocus();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
</code>```

3.Adding setOnFocusChangeListener for EditText

```<code>EmployeeId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Title: EditText, clear focus on touch outside

Body:
For Me Below things Worked -

1.Adding android:clickable="true" and android:focusableInTouchMode="true" to the parentLayout of EditTexti.e android.support.design.widget.TextInputLayout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusableInTouchMode="true">
<EditText
    android:id="@+id/employeeID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    android:hint="Employee ID"
    tools:layout_editor_absoluteX="-62dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_marginTop="42dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="36dp"
    android:layout_marginEnd="36dp" />
    </android.support.design.widget.TextInputLayout>

2.Overriding dispatchTouchEvent in Activity class and inserting hideKeyboard() function

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null && view instanceof EditText) {
                Rect r = new Rect();
                view.getGlobalVisibleRect(r);
                int rawX = (int)ev.getRawX();
                int rawY = (int)ev.getRawY();
                if (!r.contains(rawX, rawY)) {
                    view.clearFocus();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

3.Adding setOnFocusChangeListener for EditText

EmployeeId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });


问:
Pass local variable of a function back to it's parameter
I'm wanting to pass a local variable within a function, back through it's pointer parameter (not returned).

My assignment uses a stack data structure, and one criteria that must be used is the Pop() function must have a pointer parameter that is used to return the top-most item on the stack. I have used this before. My program became more complex with a data struct, I started getting either segmentation faults, or the data not being saved after the function's frame popped.

```<code>// Definitions
typedef char * string;
typedef enum { SUCCESS, FAIL } result;
typedef enum { INTEGER, DOUBLE, STRING } item_tag;

// Result Check
static result RESULT;

// Item_Tag
typedef struct {
    item_tag tag;
    union {
        int i;
        double d;
        string s;
    } value;
} item;

// Declarations
int STACK_SIZE = 0;
const int MAX_STACK_SIZE = 1024;       // Maximum stack size
item stack[1024];

// Pop
result Pop(item *ip){
    item poppedItem;
    item * pointerReturn = malloc(sizeof(item));

    // Check stack size is not 0
    if(STACK_SIZE == 0){
        return FAIL;
    }
        // If stack size is only 1, creates a blank stack
    else if(STACK_SIZE == 1){
        item emptyItem;
        // Initialize
        emptyItem.tag = INTEGER;
        emptyItem.value.i = 0;

        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;
        // Store empty stack to top of stack
        stack[0] = emptyItem;

        // Decrease stack size
        STACK_SIZE--;

    }
        // Grab top Item from stack
    else{
        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;

        // Reshuffle Items in Stack
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}
</code>```

My knowledge with pointers is alright, and memory location/management. But I can't claim to be an expert by any means. I don't exactly know what happens in the background when you're using the function's own pointer parameter as a means of passing data back.

What is the correct syntax to solve this problem?

How can a parameter pass something back?

Thanks in advance!

EDIT*
Since many people are confused. I'll post some snippets. This is an assignment, so I cannot simply post all of it online as that'd be inappropriate. But I think it's okay to post the function itself and have people analyze it. I'm aware it's a bit messy atm since I've edited it several dozen times to try and figure out the solution. Sorry for the confusion. Keep in mind that not all the code is there. just the function in question, and some of the structure.

答:
The function should receive a pointer to a valid object:

```<code>item catcher;
myFunc(&catcher);  // Pass a pointer to catcher
</code>```

and the function should modify the object it received a pointer to:

```<code>void myFunc(item *itemPointer)
{
    itemPointer->variable = stuff;
    // or
    *itemPointer = someItem;
}
</code>```

Update:

You're overcomplicating things immensely – there should be no mallocs  when popping, and you're leaking memory all over the place.

(Your knowledge of pointers and memory management is far from "alright". It looks more like a novice's guesswork than knowledge.)

It should be something more like this:

```<code>result Pop(item *ip){
    if (STACK_SIZE == 0){
        return FAIL;
    }
    else {
        *ip = stack[0];
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}
</code>```

but it's better to push/pop at the far end of the array:

```<code>result Pop(item *ip){
    if (STACK_SIZE == 0){
        return FAIL;
    }
    else {
        *ip = stack[STACK_SIZE-1];
        STACK_SIZE--;
    }
    return SUCCESS;
}
</code>```

Body:
I'm wanting to pass a local variable within a function, back through it's pointer parameter (not returned).

My assignment uses a stack data structure, and one criteria that must be used is the Pop() function must have a pointer parameter that is used to return the top-most item on the stack. I have used this before. My program became more complex with a data struct, I started getting either segmentation faults, or the data not being saved after the function's frame popped.

// Definitions
typedef char * string;
typedef enum { SUCCESS, FAIL } result;
typedef enum { INTEGER, DOUBLE, STRING } item_tag;

// Result Check
static result RESULT;

// Item_Tag
typedef struct {
    item_tag tag;
    union {
        int i;
        double d;
        string s;
    } value;
} item;

// Declarations
int STACK_SIZE = 0;
const int MAX_STACK_SIZE = 1024;       // Maximum stack size
item stack[1024];

// Pop
result Pop(item *ip){
    item poppedItem;
    item * pointerReturn = malloc(sizeof(item));

    // Check stack size is not 0
    if(STACK_SIZE == 0){
        return FAIL;
    }
        // If stack size is only 1, creates a blank stack
    else if(STACK_SIZE == 1){
        item emptyItem;
        // Initialize
        emptyItem.tag = INTEGER;
        emptyItem.value.i = 0;

        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;
        // Store empty stack to top of stack
        stack[0] = emptyItem;

        // Decrease stack size
        STACK_SIZE--;

    }
        // Grab top Item from stack
    else{
        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;

        // Reshuffle Items in Stack
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}

My knowledge with pointers is alright, and memory location/management. But I can't claim to be an expert by any means. I don't exactly know what happens in the background when you're using the function's own pointer parameter as a means of passing data back.

What is the correct syntax to solve this problem?

How can a parameter pass something back?

Thanks in advance!

EDIT*
Since many people are confused. I'll post some snippets. This is an assignment, so I cannot simply post all of it online as that'd be inappropriate. But I think it's okay to post the function itself and have people analyze it. I'm aware it's a bit messy atm since I've edited it several dozen times to try and figure out the solution. Sorry for the confusion. Keep in mind that not all the code is there. just the function in question, and some of the structure.

Body:
The function should receive a pointer to a valid object:

item catcher;
myFunc(&catcher);  // Pass a pointer to catcher

and the function should modify the object it received a pointer to:

void myFunc(item *itemPointer)
{
    itemPointer->variable = stuff;
    // or
    *itemPointer = someItem;
}

Update:

You're overcomplicating things immensely – there should be no mallocs  when popping, and you're leaking memory all over the place.

(Your knowledge of pointers and memory management is far from "alright". It looks more like a novice's guesswork than knowledge.)

It should be something more like this:

result Pop(item *ip){
    if (STACK_SIZE == 0){
        return FAIL;
    }
    else {
        *ip = stack[0];
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}

but it's better to push/pop at the far end of the array:

result Pop(item *ip){
    if (STACK_SIZE == 0){
        return FAIL;
    }
    else {
        *ip = stack[STACK_SIZE-1];
        STACK_SIZE--;
    }
    return SUCCESS;
}


问:
How to auto-refresh news feed
Hey guys, I just created a news feed and I was wondering if there was a way to auto-refresh the feed with javascript or php, sort of like facebook, without refreshing the whole page. Thanks in advance.</p>

答:
And to learn ajax i would recommend using jquery rather then reinventing the wheel. this tutorial will get you started http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

also for the php side this will be helpful http://www.w3schools.com/php/php_ajax_intro.asp

ContentLicense: CC BY-SA 2.5

Title: How to auto-refresh news feed


问:
Wrapper a dll from some link on the internet
I am trying to wrapper a dll that are in some cloud directory.

```<code> private SafeLibraryHandle sevenZipSafeHandle;

 public SevenZipHandle(string sevenZipLibPath)
    {
        this.sevenZipSafeHandle = Kernel32Dll.LoadLibrary(sevenZipLibPath);
        if (this.sevenZipSafeHandle.IsInvalid)
        {
            throw new Win32Exception();
        }
  }
}

 internal static class Kernel32Dll
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern SafeLibraryHandle LoadLibrary([MarshalAs(UnmanagedType.LPTStr)] string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [MarshalAs(UnmanagedType.LPStr)] string procName);

    [SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool FreeLibrary(IntPtr hModule);
}
</code>```

I am validating a dll file, but if I use :

```<code>sevenZipLibPath  = “c:/temp/file.dll”
</code>```

it works fine.

But if use some file that is on the internet like:

```<code>sevenZipLibPath  = “"http://any.blob.core.windows.net/files/file.dll”
</code>```

it does not work.

How can I check a DLL file from some cloud drive in that situation?

答:
The LoadLibrary function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
Only supports filepaths, not urls.

So download it first to a temporary location. You can also do that in code using the webclient class.
A simple example:
https://stackoverflow.com/a/525372/4640588

Edit - Example using the paths you provided

```<code>using (WebClient client = new WebClient())
{
    client.DownloadFile(
        "http://any.blob.core.windows.net/files/file.dll",
        "c:/temp/file.dll");
}
</code>```

Validate it, then delete it afterwards.

Body:
I am trying to wrapper a dll that are in some cloud directory.

 private SafeLibraryHandle sevenZipSafeHandle;

 public SevenZipHandle(string sevenZipLibPath)
    {
        this.sevenZipSafeHandle = Kernel32Dll.LoadLibrary(sevenZipLibPath);
        if (this.sevenZipSafeHandle.IsInvalid)
        {
            throw new Win32Exception();
        }
  }
}

 internal static class Kernel32Dll
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern SafeLibraryHandle LoadLibrary([MarshalAs(UnmanagedType.LPTStr)] string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [MarshalAs(UnmanagedType.LPStr)] string procName);

    [SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool FreeLibrary(IntPtr hModule);
}

I am validating a dll file, but if I use :

sevenZipLibPath  = “c:/temp/file.dll”

it works fine.

But if use some file that is on the internet like:

sevenZipLibPath  = “"http://any.blob.core.windows.net/files/file.dll”

it does not work.

How can I check a DLL file from some cloud drive in that situation?

Body:
The LoadLibrary function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
Only supports filepaths, not urls.

So download it first to a temporary location. You can also do that in code using the webclient class.
A simple example:
https://stackoverflow.com/a/525372/4640588

Edit - Example using the paths you provided

using (WebClient client = new WebClient())
{
    client.DownloadFile(
        "http://any.blob.core.windows.net/files/file.dll",
        "c:/temp/file.dll");
}

Validate it, then delete it afterwards.


问:
Pros and Cons of running two SQL instances to separate frontend / backend traffic (some of which is sensitive)?
I am a new developer, building a website with Node / Angular / MariaDB.  I am just now starting to use MariaDB in this project.

I understand at this point that it is best to use a backend as a middle-man between sensitive SQL data and the frontend.  However, most SQL data will not be sensitive data, i.e., nutritional information and recipes.

Question

With these two sets of SQL data, it seems like there are two scenarios that I can pursue:

One MariaDB install on one server: all data, sensitive or not, passed through the backend to the frontend user.

Two MariaDB installs on one server: sensitive data is passed through the backend, non-sensitive data is queried directly by the frontend.

What are the pros and cons of these two scenarios?

Are there other factors to take into consideration?

What additional information would help me evaluate which would be the best practice for my project?

Additional questions that I think may be of interest would be whether two SQL installs present other issues (I imagine that these would need to be containerized or virtualized).

Thank you for reading, have a nice day.

答:
There's a good point to say that this might be an opinion question and should be closed.

But I think there's a single realistic approach here - to put everything behind a web service and not expose anything about the database to the frontend.

There's several reasons for this:

At the least, you might want to have some sort of caching at some point, and that's best handled by an intermediate layer, to keep clients simpler.

General rules about logging, identity, DDoS protection etc. should be handled at the entry to your system, rather than distributed about each component.

AFAIK, from the browser you can only open http and web socket connections to the database, which is not sufficient to speak to a MariaDB instance, which expects to be contacted via TCP/IP with it's specific protocol.

Security wise, having an live database accessible to anyone might open it to things like XSS attacks - people managing to insert malicious data into the database, which is then executed with the credentials of other users.


问:
PostgreSQL - max number of parameters in "IN" clause?
In Postgres, you can specify an IN clause, like this:

```<code>SELECT * FROM user WHERE id IN (1000, 1001, 1002)
</code>```

Does anyone know what's the maximum number of parameters you can pass into IN?

答:
As someone more experienced with Oracle DB, I was concerned about this limit too. I carried out a performance test for a query with ~10'000 parameters in an IN-list, fetching prime numbers up to 100'000 from a table with the first 100'000 integers by actually listing all the prime numbers as query parameters.

My results indicate that you need not worry about overloading the query plan optimizer or getting plans without index usage, since it will transform the query to use = ANY({...}::integer[]) where it can leverage indices as expected:

```<code>-- prepare statement, runs instantaneous:
PREPARE hugeplan (integer, integer, integer, ...) AS
SELECT *
FROM primes
WHERE n IN ($1, $2, $3, ..., $9592);

-- fetch the prime numbers:
EXECUTE hugeplan(2, 3, 5, ..., 99991);

-- EXPLAIN ANALYZE output for the EXECUTE:
"Index Scan using n_idx on primes  (cost=0.42..9750.77 rows=9592 width=5) (actual time=0.024..15.268 rows=9592 loops=1)"
"  Index Cond: (n = ANY ('{2,3,5,7, (...)"
"Execution time: 16.063 ms"

-- setup, should you care:
CREATE TABLE public.primes
(
  n integer NOT NULL,
  prime boolean,
  CONSTRAINT n_idx PRIMARY KEY (n)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.primes
  OWNER TO postgres;

INSERT INTO public.primes
SELECT generate_series(1,100000);
</code>```

However, this (rather old) thread on the pgsql-hackers mailing list indicates that there is still a non-negligible cost in planning such queries, so take my word with a grain of salt.

Body:
In Postgres, you can specify an IN clause, like this:

SELECT * FROM user WHERE id IN (1000, 1001, 1002)

Does anyone know what's the maximum number of parameters you can pass into IN?

Body:
As someone more experienced with Oracle DB, I was concerned about this limit too. I carried out a performance test for a query with ~10'000 parameters in an IN-list, fetching prime numbers up to 100'000 from a table with the first 100'000 integers by actually listing all the prime numbers as query parameters.

My results indicate that you need not worry about overloading the query plan optimizer or getting plans without index usage, since it will transform the query to use = ANY({...}::integer[]) where it can leverage indices as expected:

-- prepare statement, runs instantaneous:
PREPARE hugeplan (integer, integer, integer, ...) AS
SELECT *
FROM primes
WHERE n IN ($1, $2, $3, ..., $9592);

-- fetch the prime numbers:
EXECUTE hugeplan(2, 3, 5, ..., 99991);

-- EXPLAIN ANALYZE output for the EXECUTE:
"Index Scan using n_idx on primes  (cost=0.42..9750.77 rows=9592 width=5) (actual time=0.024..15.268 rows=9592 loops=1)"
"  Index Cond: (n = ANY ('{2,3,5,7, (...)"
"Execution time: 16.063 ms"

-- setup, should you care:
CREATE TABLE public.primes
(
  n integer NOT NULL,
  prime boolean,
  CONSTRAINT n_idx PRIMARY KEY (n)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.primes
  OWNER TO postgres;

INSERT INTO public.primes
SELECT generate_series(1,100000);

However, this (rather old) thread on the pgsql-hackers mailing list indicates that there is still a non-negligible cost in planning such queries, so take my word with a grain of salt.

ContentLicense: CC BY-SA 4.0


问:
I am not able to scroll to elements below the list view. How to view those
I am using a ScrollView inside which I am using RelativeLayout inside which I am using ListView inside HorizontalScrollView. Now after that i am placing a button but not able to scroll to that button as the page is not scrolling, just the ListView is scrolling.

I want the list to scroll and after the list is finished the page should scroll so that i can see the button to click it

how to do that

I am sharing my xml that I have made so far

main.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:id="@+id/hori_scroll_view"
        android:layout_below="@+id/heading2"
        android:layout_marginTop="20dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/list"/>

    </HorizontalScrollView>

    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/hori_scroll_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />

</RelativeLayout>
</ScrollView>
</code>```

答: Are you trying to scroll horizontally/ vertically with list view. If you are trying to scroll vertically you have to use NestedScrollView and RecyclerView with in it. </p>

Body:
I am using a ScrollView inside which I am using RelativeLayout inside which I am using ListView inside HorizontalScrollView. Now after that i am placing a button but not able to scroll to that button as the page is not scrolling, just the ListView is scrolling.

I want the list to scroll and after the list is finished the page should scroll so that i can see the button to click it

how to do that

I am sharing my xml that I have made so far

main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:id="@+id/hori_scroll_view"
        android:layout_below="@+id/heading2"
        android:layout_marginTop="20dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/list"/>

    </HorizontalScrollView>

    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/hori_scroll_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />

</RelativeLayout>
</ScrollView>


问:
Why `minimum (1, 2)` returns 2 in Haskell?
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

```<code>GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2
</code>```

Shouldn't it return 1?

答:
The type of minimum is

```<code> (Ord a, Foldable t) => t a -> a
</code>```

The Foldable instance for pairs refers only to the second element of the pair, which you can see with toList:

```<code>toList (1,2)
> [2]
</code>```

the minimum element in that collection is 2.

Body:
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2

Shouldn't it return 1?

Body:
The type of minimum is

 (Ord a, Foldable t) => t a -> a

The Foldable instance for pairs refers only to the second element of the pair, which you can see with toList:

toList (1,2)
> [2]

the minimum element in that collection is 2.


问:
Flutter listview headers
I want to make a listview with headers per day, like the google calendar and the google contacts. I couldn't find an example how to make something like this in a flutter view.
So I want to have a header stick on the left side such as the date for the first item with that date till the next day gets on top and then the previous day has to continue to scroll. Should I work with a MultiChildLayoutDelegate like the animation example in the gallery or can I do this with the listview in some way?

Edit: Made a package myself: https://pub.dartlang.org/packages/side_header_list_view

答:
For everybody looking for a solution, I just made a library that does this:
https://pub.dartlang.org/packages/side_header_list_view

You can look for the code on github:
https://github.com/renefloor/side_header_list_view

Basically I show/hide the header part of a listitem depending on the position and added a fixed header on the top left. For now the listitems have to have a fixed height.

Title: Flutter listview headers


问:
how to style a nav bar, logo and title in angular bootstrap 4 web app?
Im trying to make the top of the webpage so its a grid of ratio 3:6 with the section on the left being a square image. and the section on the right being split horizontally in 2 with the top half being a bar with the title and the bottom half a naviagtion bar. this is my code. unfortuanetly the title is not appearing at all, and the image is appearing on top of the navigation bar and also not filling the width of the screen. Im really not sure what the problem. any help would be great! thanks

```<code> <div class="col-sm-6 col-md-3 col-lg-3 col-xl-3">
   <img ng-src="img/sky-logo.jpg" width="200px"/>
  </div>

  <div class="col-sm-6 col-md-9 col-lg-9 col-xl-9 ">

    <div id="top">
    <div class="container">
    <div class="clearfix">
      <div class="pull-center"><title> title </title></div>
    </div>
    </div>
    </div>

  <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <ul class="navbar-nav">
  <li class="nav-item">
  <a class="nav-link" href="#link1">link 1</a>
  </li>
  <li class="nav-item">
  <a class="nav-link" href="#link2">link 2</a>
  </li>
  </ul>
 </nav>

 </div>
     <div ng-view></div>
 </body>
</code>```

答:
for title you should use headings instead as <title> tag defines a title in the browser toolbar and should be placed in

for layout that you described you can try the following code

```<code> <div class="col-sm-12">
        <!-- for ratio 3:6 -->
        <div class="col-sm-4">
            <img ng-src="img/sky-logo.jpg" style="width:200px" />
        </div>
        <!-- for ratio 3:6 -->
        <div class="col-sm-8">
            <!-- top half -->
            <div class="col-sm-12">
                <div id="top">
                    <div class="container">
                        <div class="clearfix">
                            <div class="pull-center">title</div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- bottom half -->
            <div class="col-sm-12">
                <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link" href="#link1">link 1</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#link2">link 2</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</code>```

Body:
Im trying to make the top of the webpage so its a grid of ratio 3:6 with the section on the left being a square image. and the section on the right being split horizontally in 2 with the top half being a bar with the title and the bottom half a naviagtion bar. this is my code. unfortuanetly the title is not appearing at all, and the image is appearing on top of the navigation bar and also not filling the width of the screen. Im really not sure what the problem. any help would be great! thanks

<title> title </title>

  link 1

  link 2

Body:
for title you should use headings instead as <title> tag defines a title in the browser toolbar and should be placed in <head></head>

for layout that you described you can try the following code

 <div class="col-sm-12">
        <!-- for ratio 3:6 -->
        <div class="col-sm-4">
            <img ng-src="img/sky-logo.jpg" style="width:200px" />
        </div>
        <!-- for ratio 3:6 -->
        <div class="col-sm-8">
            <!-- top half -->
            <div class="col-sm-12">
                <div id="top">
                    <div class="container">
                        <div class="clearfix">
                            <div class="pull-center">title</div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- bottom half -->
            <div class="col-sm-12">
                <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link" href="#link1">link 1</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#link2">link 2</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>


问:
Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
I'm trying to follow this youtube video tutorial and at the 8:22 point of the video, I am running into the following error:

Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

This his how the information is stored in firebase.

The data is set in firebase by a profile.html page.

```<code><ion-content padding>
    <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input [(ngModel)]="profile.username"></ion-input>
    </ion-item>
    <ion-item>
        <ion-label floating>First Name</ion-label>
        <ion-input [(ngModel)]="profile.firstname"></ion-input>
    </ion-item>
    <ion-item>
        <ion-label floating>Last Name</ion-label>
        <ion-input [(ngModel)]="profile.lastname"></ion-input>
    </ion-item>

    <button ion-button block (click)="createProfile()">Create Profile</button>

</ion-content>
</code>```

this profile.ts looks like this

```<code>import { Profile } from '../../models/profile';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the ProfilePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {

    profile = {} as Profile;

  constructor(
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    public navCtrl: NavController,
    public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ProfilePage');
  }

  createProfile(){
    this.afAuth.authState.take(1).subscribe(auth => {
        this.afDatabase.object(`profile/${auth.uid}`).set(this.profile)
        .then(() => this.navCtrl.setRoot('HomePage'));
    })
  }

}
</code>```

The models/profile.ts looks like:

```<code>export interface Profile {
    username: string;
    firstName: string;
    lastName: string;
}
</code>```

At this point in the tutorial we are just simply trying to display the username on the homepage.

My home.ts file looks like this:

```<code>import { Item } from './../../models/item/item.model';
import { Profile } from './../../models/profile';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import { Component } from '@angular/core';
import { NavController, IonicPage, ToastController } from 'ionic-angular';
import { ShoppingListService } from '../../services/shopping-list/shopping-list.service';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';

@IonicPage()

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  profileData: FirebaseObjectObservable<Profile>
    shoppingList$: Observable<Item[]>

  constructor(
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    private toast: ToastController,
    public navCtrl: NavController,
    private shopping:ShoppingListService) {
    this.shoppingList$ = this.shopping
        .getShoppingList()
        .snapshotChanges()
        .map(
            changes => {
                return changes.map(c => ({
                    key: c.payload.key, ...c.payload.val()
                }));
            });
  }

  ionViewWillLoad(){
      this.afAuth.authState.subscribe(data => {
        if(data && data.email && data.uid){
          this.toast.create({
            message: `Welcome to the Jungle, ${data.email}`,
            duration: 3000
          }).present();
          this.profileData = this.afDatabase.object(`profile/${data.uid}`)

        } else {
        this.toast.create({
            message: `Could not log you in`,
            duration: 3000
          }).present();
      }
    }
  )}
</code>```

My home.html page looks like this:

```<code><ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Shopping List
    </ion-title>
    <ion-buttons end>
        <button navPush='AddShoppingItemPage' ion-button>
            <ion-icon name="add"></ion-icon>
        </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <p>Username: {{(profileData | async)?.username}}</p>
  <ion-list>
    <ion-list-header>
      Items
    </ion-list-header>
    <ion-item *ngFor="let item of shoppingList$ | async" detail-push navPush="EditShoppingItemPage" [navParams]="{item: item}">
      {{item.name}}
    </ion-item>
  </ion-list>
</ion-content>
</code>```

It seems as though either this line in home.ts:

```<code>this.profileData = this.afDatabase.object(`profile/${data.uid}`)
</code>```

or this line:

```<code>profileData: AngularFireObject<Profile>
</code>```

or this line:

```<code>import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
</code>```

is the culprit.

However, I'm not sure how to fix it. I have followed the tutorial exactly as the author has instructed, and it works fine for him. The tutorial is only 5 months old. I know that the technology is changing rapidly and 5 months is a long time, but its advancing so quickly that it makes learning it impossible as all the tutorials are broken immediately after they are published. You spend more time fixing errors that as a beginner you don't understand and can't comprehend.

答:
The profileData property is not an observable so you can't use the async pipe with it.

Update your template with the following:

```<code>  <p>Username: {{profileData?.username}}</p>
</code>```

Body:
I'm trying to follow this youtube video tutorial and at the 8:22 point of the video, I am running into the following error:

Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

This his how the information is stored in firebase.

The data is set in firebase by a profile.html page.

<ion-content padding>
    <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input [(ngModel)]="profile.username"></ion-input>
    </ion-item>
    <ion-item>
        <ion-label floating>First Name</ion-label>
        <ion-input [(ngModel)]="profile.firstname"></ion-input>
    </ion-item>
    <ion-item>
        <ion-label floating>Last Name</ion-label>
        <ion-input [(ngModel)]="profile.lastname"></ion-input>
    </ion-item>

    <button ion-button block (click)="createProfile()">Create Profile</button>

</ion-content>

this profile.ts looks like this

import { Profile } from '../../models/profile';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the ProfilePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {

    profile = {} as Profile;

  constructor(
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    public navCtrl: NavController,
    public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ProfilePage');
  }

  createProfile(){
    this.afAuth.authState.take(1).subscribe(auth => {
        this.afDatabase.object(`profile/${auth.uid}`).set(this.profile)
        .then(() => this.navCtrl.setRoot('HomePage'));
    })
  }

}

The models/profile.ts looks like:

export interface Profile {
    username: string;
    firstName: string;
    lastName: string;
}

At this point in the tutorial we are just simply trying to display the username on the homepage.

My home.ts file looks like this:

import { Item } from './../../models/item/item.model';
import { Profile } from './../../models/profile';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import { Component } from '@angular/core';
import { NavController, IonicPage, ToastController } from 'ionic-angular';
import { ShoppingListService } from '../../services/shopping-list/shopping-list.service';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';

@IonicPage()

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  profileData: FirebaseObjectObservable<Profile>
    shoppingList$: Observable<Item[]>

  constructor(
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    private toast: ToastController,
    public navCtrl: NavController,
    private shopping:ShoppingListService) {
    this.shoppingList$ = this.shopping
        .getShoppingList()
        .snapshotChanges()
        .map(
            changes => {
                return changes.map(c => ({
                    key: c.payload.key, ...c.payload.val()
                }));
            });
  }

  ionViewWillLoad(){
      this.afAuth.authState.subscribe(data => {
        if(data && data.email && data.uid){
          this.toast.create({
            message: `Welcome to the Jungle, ${data.email}`,
            duration: 3000
          }).present();
          this.profileData = this.afDatabase.object(`profile/${data.uid}`)

        } else {
        this.toast.create({
            message: `Could not log you in`,
            duration: 3000
          }).present();
      }
    }
  )}

My home.html page looks like this:

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Shopping List
    </ion-title>
    <ion-buttons end>
        <button navPush='AddShoppingItemPage' ion-button>
            <ion-icon name="add"></ion-icon>
        </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content padding>

Username: {{(profileData | async)?.username}}

  <ion-list>
    <ion-list-header>
      Items
    </ion-list-header>
    <ion-item *ngFor="let item of shoppingList$ | async" detail-push navPush="EditShoppingItemPage" [navParams]="{item: item}">
      {{item.name}}
    </ion-item>
  </ion-list>
</ion-content>

It seems as though either this line in home.ts:

this.profileData = this.afDatabase.object(`profile/${data.uid}`)

or this line:

profileData: AngularFireObject<Profile>

or this line:

import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';

is the culprit.

However, I'm not sure how to fix it. I have followed the tutorial exactly as the author has instructed, and it works fine for him. The tutorial is only 5 months old. I know that the technology is changing rapidly and 5 months is a long time, but its advancing so quickly that it makes learning it impossible as all the tutorials are broken immediately after they are published. You spend more time fixing errors that as a beginner you don't understand and can't comprehend.

Body:
The profileData property is not an observable so you can't use the async pipe with it.

Update your template with the following:

  <p>Username: {{profileData?.username}}</p>


问:
How to grant Google compute engine instance access to a cloud storage bucket?
I have a compute engine instance (Ubuntu 16.04) and a storage bucket both in the same project.

I want to mount the storage on the compute instance. I found some resources on this page: https://cloud.google.com/storage/docs/gcs-fuse.

I already installed gcsfuse on the instance and created a directory to mount the storage like this:

```<code>cd $HOME
mkdir storage
</code>```

Then I mounted the storage using the gcsfuse command:

```<code>gcsfuse storage-bucket storage/
</code>```

According the gcsfuse output everything looks solid, but when I try to create a test file like:

```<code>touch storage/test.txt
</code>```

I get the following error:

```<code>touch: cannot touch 'storage/test.txt': Input/output error
</code>```

I'm kinda stuck at the moment, what else should I try?

答:
Thanks everyone for the support, meanwhile based on this article I managed to set it up for me:

https://www.assistanz.com/mount-google-cloud-storage-bucket-linux/

Also when I created the instance I set the Access scopes to Allow full acces to all Cloud APIs and now it works like a charm!

Body:
I have a compute engine instance (Ubuntu 16.04) and a storage bucket both in the same project.

I want to mount the storage on the compute instance. I found some resources on this page: https://cloud.google.com/storage/docs/gcs-fuse.

I already installed gcsfuse on the instance and created a directory to mount the storage like this:

cd $HOME
mkdir storage

Then I mounted the storage using the gcsfuse command:

gcsfuse storage-bucket storage/

According the gcsfuse output everything looks solid, but when I try to create a test file like:

touch storage/test.txt

I get the following error:

touch: cannot touch 'storage/test.txt': Input/output error

I'm kinda stuck at the moment, what else should I try?


问:
Is std::ifstream significantly slower than FILE?
I've been informed that my library is slower than it should be, on the order of 30+ times too slow parsing a particular file (text file, size 326 kb). The user suggested that it may be that I'm using std::ifstream (presumably instead of FILE).

I'd rather not blindly rewrite, so I thought I'd check here first, since my guess would be the bottleneck is elsewhere. I'm reading character by character, so the only functions I'm using are get(), peek(), and tellg()/seekg().

Update:

I profiled, and got confusing output - gprof didn't appear to think that it took so long. I rewrote the program to read the entire file into a buffer first, and it sped up by about 100x. I think the problem may have been the tellg()/seekg() that took a long time, but gprof may have been unable to see that for some reason. In any case, ifstream does not appear to buffer the entire file, even for this size.

答:
I thinks that is unlikely your problem will be fixed by switching from fstream to FILE*, usually both are buffered by the C library. Also the OS can cache reads (linux is very good in that aspect). Given the size of the file you are accessing is pretty likely it will be entirely in RAM.

Like PolyThinker say your best bet is to run your program trough an profiler an determine where the problem is.

Also you are using seekg/tellg this can cause notable delays if your disk is heavily fragmented, because to read the file for the first time the disk have to move the heads to the correct position.

OwnerDisplayName: Jesse Beder

LastEditorDisplayName: Jesse Beder

OwnerDisplayName: xhantt


问:
How to display multiple consoles and Projects in Intellij Idea
In Intellij Idea, is there a way to show 2 consoles side by side at the same time?
And can it Idea open multiple projects in one window?
Below picture of Eclipse is what I want.
Thanks!

screenshot of multiple consoles and Projects in Eclipse

答:
please check Migrating From Eclipse to IntelliJ IDEA
https://www.jetbrains.com/help/idea/eclipse.html</p>


问:
How to replace NA values in a table for selected columns
There are a lot of posts about replacing NA values. I am aware that one could replace NAs in the following table/frame with the following:

```<code>x[is.na(x)]<-0
</code>```

But, what if I want to restrict it to only certain columns? Let's me show you an example.

First, let's start with a dataset.

```<code>set.seed(1234)
x <- data.frame(a=sample(c(1,2,NA), 10, replace=T),
                b=sample(c(1,2,NA), 10, replace=T),
                c=sample(c(1:5,NA), 10, replace=T))
</code>```

Which gives:

```<code>    a  b  c
1   1 NA  2
2   2  2  2
3   2  1  1
4   2 NA  1
5  NA  1  2
6   2 NA  5
7   1  1  4
8   1  1 NA
9   2  1  5
10  2  1  1
</code>```

Ok, so I only want to restrict the replacement to columns 'a' and 'b'. My attempt was:

```<code>x[is.na(x), 1:2]<-0
</code>```

and:

```<code>x[is.na(x[1:2])]<-0
</code>```

Which does not work.

My data.table attempt, where y<-data.table(x), was obviously never going to work:

```<code>y[is.na(y[,list(a,b)]), ]
</code>```

I want to pass columns inside the is.na argument but that obviously wouldn't work.

I would like to do this in a data.frame and a data.table. My end goal is to recode the 1:2 to 0:1 in 'a' and 'b' while keeping 'c' the way it is, since it is not a logical variable. I have a bunch of columns so I don't want to do it one by one. And, I'd just like to know how to do this.

Do you have any suggestions?

答:
This is now trivial in tidyr with replace_na(). The function appears to work for data.tables as well as data.frames:

```<code>tidyr::replace_na(x, list(a=0, b=0))
</code>```

Body:
There are a lot of posts about replacing NA values. I am aware that one could replace NAs in the following table/frame with the following:

x[is.na(x)]<-0

But, what if I want to restrict it to only certain columns? Let's me show you an example.

First, let's start with a dataset.

set.seed(1234)
x <- data.frame(a=sample(c(1,2,NA), 10, replace=T),
                b=sample(c(1,2,NA), 10, replace=T),
                c=sample(c(1:5,NA), 10, replace=T))

Which gives:

    a  b  c
1   1 NA  2
2   2  2  2
3   2  1  1
4   2 NA  1
5  NA  1  2
6   2 NA  5
7   1  1  4
8   1  1 NA
9   2  1  5
10  2  1  1

Ok, so I only want to restrict the replacement to columns 'a' and 'b'. My attempt was:

x[is.na(x), 1:2]<-0

and:

x[is.na(x[1:2])]<-0

Which does not work.

My data.table attempt, where y<-data.table(x), was obviously never going to work:

y[is.na(y[,list(a,b)]), ]

I want to pass columns inside the is.na argument but that obviously wouldn't work.

I would like to do this in a data.frame and a data.table. My end goal is to recode the 1:2 to 0:1 in 'a' and 'b' while keeping 'c' the way it is, since it is not a logical variable. I have a bunch of columns so I don't want to do it one by one. And, I'd just like to know how to do this.

Do you have any suggestions?

Body:
This is now trivial in tidyr with replace_na(). The function appears to work for data.tables as well as data.frames:

tidyr::replace_na(x, list(a=0, b=0))


问:
How to use token authentication while testing REST API
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

```<code>@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200
</code>```

and this is how I use it:

```<code>def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK
</code>```

It gives me 401 error. What is the correct way of using token?

答:
According to official documentation the the token key should be Authentication and the token should be should be trailing Token and a white space.
In your code change token {} to  Token {}.
If the problem persists try to print request headers in you view by printing request.META to check the key.</p>

Body:
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200

and this is how I use it:

def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK

It gives me 401 error. What is the correct way of using token?


问:
Disconnect from Slick JNDI connection in Play for Scala
Slick defines here how to connect to a database using JNDI:

```<code>val db = Database.forName(jndiName: String)
</code>```

I use the above to connect to a database in Play for Scala, defining the JNDI connection in application.conf:

```<code>   def read (jndi: String, code: Int) = {
      val db = Database.forName(jndi)
      val records = TableQuery[TableDB]
      val action = records.filter(_.code === code).result
      val future = db.run(action.asTry)
      future.map{
        case Success(s) =>
          if (s.length>0)
            Some(s(0))
          else
            None
        case Failure(e) => throw new Exception ("Failure in read: " + e.getMessage)
      }
   }
</code>```

Question is: how to disconnect from the JNDI resource? Simply db.close() ? Is there a way to implicitly close the connection when the read method ends?

答:
You can always use play's shutdown hooks to close the db connection when you app shuts down (which is usually what you would want) and yes db.close is enough to stop the connection, your port will be freed which is all you should care about. I'm not quite sure why you would want the db to close right after the method, but there's a very easy fix to this without polluting the code, you simply inject your database into the method :

```<code>def read(db : Database, code: Int) = {
    val records = TableQuery[TableDB]
    val action = records.filter(_.code === code).result
    val future = db.run(action.asTry)
    future.map {
      case Success(s) =>
        if (s.length > 0)
          Some(s(0))
        else
          None
      case Failure(e) => throw new Exception("Failure in read: " + e.getMessage)

  }
</code>```

And the caller of this method can close the respective database once you have the results you want. Much safer and easier to change :) On the other hand, you can always go with @SergGr's solution, it also works :)

Body:
Slick defines here how to connect to a database using JNDI:

val db = Database.forName(jndiName: String)

I use the above to connect to a database in Play for Scala, defining the JNDI connection in application.conf:

   def read (jndi: String, code: Int) = {
      val db = Database.forName(jndi)
      val records = TableQuery[TableDB]
      val action = records.filter(_.code === code).result
      val future = db.run(action.asTry)
      future.map{
        case Success(s) =>
          if (s.length>0)
            Some(s(0))
          else
            None
        case Failure(e) => throw new Exception ("Failure in read: " + e.getMessage)
      }
   }

Question is: how to disconnect from the JNDI resource? Simply db.close() ? Is there a way to implicitly close the connection when the read method ends?

Body:
You can always use play's shutdown hooks to close the db connection when you app shuts down (which is usually what you would want) and yes db.close is enough to stop the connection, your port will be freed which is all you should care about. I'm not quite sure why you would want the db to close right after the method, but there's a very easy fix to this without polluting the code, you simply inject your database into the method :

def read(db : Database, code: Int) = {
    val records = TableQuery[TableDB]
    val action = records.filter(_.code === code).result
    val future = db.run(action.asTry)
    future.map {
      case Success(s) =>
        if (s.length > 0)
          Some(s(0))
        else
          None
      case Failure(e) => throw new Exception("Failure in read: " + e.getMessage)

  }

And the caller of this method can close the respective database once you have the results you want. Much safer and easier to change :) On the other hand, you can always go with @SergGr's solution, it also works :)


问:
Different Versions of the same Library in maven
Is it possible to use in java program a library with two different versions ?

Maven Dependency

```<code><artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>2.0.10</version>
</code>```

and

```<code><artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>2.0.7</version>
</code>```

version 2.0.10 contains some features which are not available in 2.0.7 but it not supports $filter=startswith.
Two versions contains same classes and interfaces

答:
Mostly that is not a good idea as you have no control (without major effort) on which dependency will be first on the classpath.
You will only be able to access the first found on the classpath and you might get weird errors. e.g. like MethodNotFoundExceptions and the like

Think about upgrading if at all possible.

Body:
Is it possible to use in java program a library with two different versions ?

Maven Dependency

<artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>2.0.10</version>

and

<artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>2.0.7</version>

version 2.0.10 contains some features which are not available in 2.0.7 but it not supports $filter=startswith.
Two versions contains same classes and interfaces


问:
Fill data frame by column with for loop
I created an empty data frame with 11 columns and 15 rows and subsequently named the columns.

```<code>L_df <- data.frame(matrix(ncol = 11, nrow = 15))
names(L_df) <- paste0("L_por", 0:10)

w <- c(0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6,  2.8, 3)
wu <- 0
L <- 333.7
pm <- c(2600, 2574, 2548, 2522, 2496, 2470, 2444, 2418, 2392, 2366,  2340)
</code>```

The data frame looks like this:

```<code>head(L_df)
  L_por0 L_por1 L_por2 L_por3 L_por4 L_por5 L_por6 L_por7 L_por8 L_por9 L_por10
1     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
2     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
3     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
4     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
5     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
6     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
</code>```

Now, I would like to fill the data frame by column, based on a formula.  I tried to express this with a nested for loop:

```<code> for (i in 1:ncol(L_df)) {
  pm_tmp <- pm[i]
  col_tmp <- colnames(L_df)[i]
  for (j in 1:nrow(L_df)) {
    w_tmp <- w[j]
    L_por_tmp <- pm_tmp*L*((w_tmp-wu)/100)
    col_tmp[j] <- L_por_tmp
  }
}
</code>```

For each column, I iterate over a predefined vector pm of length 11. For each row, I iterate over a predefined vector w of length 15 (repeats each column).

Example: First, select pm[1] for the first column. Second, select w[i] for each row in the first column. Store the formula in L_por_tmp and use it to fill the first column from row1 to row15. The whole procedure should start all over again for the second column (with pm[2]) with w[i] for each row and so on. wu and L are fixed in the formula.

R executes the code without an error. When I check the tmp values, they are correct. However, the data frame remains empty. L_df does not get filled. I would like solve this with a loop but if you have other solutions, I am happy to hear them! I get the impression there might be a smoother way of doing this. Cheers!

Title: Fill data frame by column with for loop

Body:
I created an empty data frame with 11 columns and 15 rows and subsequently named the columns.

L_df <- data.frame(matrix(ncol = 11, nrow = 15))
names(L_df) <- paste0("L_por", 0:10)

w <- c(0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6,  2.8, 3)
wu <- 0
L <- 333.7
pm <- c(2600, 2574, 2548, 2522, 2496, 2470, 2444, 2418, 2392, 2366,  2340)

The data frame looks like this:

head(L_df)
  L_por0 L_por1 L_por2 L_por3 L_por4 L_por5 L_por6 L_por7 L_por8 L_por9 L_por10
1     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
2     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
3     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
4     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
5     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
6     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA

Now, I would like to fill the data frame by column, based on a formula.  I tried to express this with a nested for loop:

 for (i in 1:ncol(L_df)) {
  pm_tmp <- pm[i]
  col_tmp <- colnames(L_df)[i]
  for (j in 1:nrow(L_df)) {
    w_tmp <- w[j]
    L_por_tmp <- pm_tmp*L*((w_tmp-wu)/100)
    col_tmp[j] <- L_por_tmp
  }
}

For each column, I iterate over a predefined vector pm of length 11. For each row, I iterate over a predefined vector w of length 15 (repeats each column).

Example: First, select pm[1] for the first column. Second, select w[i] for each row in the first column. Store the formula in L_por_tmp and use it to fill the first column from row1 to row15. The whole procedure should start all over again for the second column (with pm[2]) with w[i] for each row and so on. wu and L are fixed in the formula.

R executes the code without an error. When I check the tmp values, they are correct. However, the data frame remains empty. L_df does not get filled. I would like solve this with a loop but if you have other solutions, I am happy to hear them! I get the impression there might be a smoother way of doing this. Cheers!

Body:
You are just doing a small mistake and you were almost there, Edited your function:

for (i in 1:ncol(L_df)) {
  pm_tmp <- pm[i]
  col_tmp <- colnames(L_df)[i]
  for (j in 1:nrow(L_df)) {
    w_tmp <- w[j]
    L_por_tmp <- pm_tmp*L*((w_tmp-wu)/100)
    L_df[ j ,col_tmp] <- L_por_tmp ##You must have used df[i, j] referencing here
  }
}

Output:

Just printing the head of few rows:

L_df
     L_por0    L_por1    L_por2    L_por3    L_por4    L_por5    L_por6    L_por7    L_por8    L_por9   L_por10
1   1735.24  1717.888  1700.535  1683.183  1665.830  1648.478  1631.126  1613.773  1596.421  1579.068  1561.716
2   3470.48  3435.775  3401.070  3366.366  3331.661  3296.956  3262.251  3227.546  3192.842  3158.137  3123.432
3   5205.72  5153.663  5101.606  5049.548  4997.491  4945.434  4893.377  4841.320  4789.262  4737.205  4685.148


问:
EclipseLink/JPA: Merge on detached object tree causes primary key violation in child object
I have a problem with JPA and detached entity objects passed from outside the application via JSON deserialization.

I deserialize an object graph from JSON (passed through a HTTP POST request) and then try to update an existing entity from it.

As far as I understand JPA, using EntityManager.merge() on an object should automatically and recursively (depending on cascade) attach it and issue an UPDATE to the DB for all the objects in the tree.
However, this apparently only works well for 1) a single entity with no children or 2) the topmost entity in an object graph.

For the child entities, JPA will always issue an INSERT INTO, regardless if the object is already there, and thus run into a primary key violation.

What am I doing wrong?

The relevant part of the implementation is this:

In AdminResource.java:

```<code>@Autowire
protected CustomerConfigDAO customerConfigDao; // wrapper for the JPA persistence

@POST
@Consumes(MediaType.APPLICATION_JSON)
public void storeConfigurationData(CustomerConfigEntity config) {
    customerConfigDao.update(config); // calls EntityManager.merge(...)
}
</code>```

In CustomerConfigEntity.java:

```<code>@Entity
public class CustomerConfigEntity implements Serializable {

    @Id
    private String customerID;

    @OneToOne(mappedBy = "customerConfigEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private DefaultValues defaultValues;

    /* ... snip ... */

    @PrePersist
    @PreUpdate
    public void fixBackReference() {
        if(this.defaultValues != null)
            this.defaultValues.setCustomerConfigEntity(this);
    }
}
</code>```

In DefaultValues.java:

```<code>@Entity
public class DefaultValues implements Serializable {

    @Id
    @OneToOne
    @JoinColumn(name = "customerID", referencedColumnName = "cloudID")
    @JsonIgnore
    private CustomerConfigEntity customerConfigEntity;

    /* ... snip ... */

}
</code>```

Someone suggested to drop the bi-directional one-to-one relationship in favour of a uni-directional one, but since customerConfigEntity is both the foreign AND the primary key in DefaultValues, removing it would require me to introduce a surrogate key. I did this by introducing an auto-incremented key, but the result was that JPA would create a new record in DEFAULTVALUES whenever a CustomerConfigEntity was saved.

答:
I solved the problem by eliminating all the bi-directional relationships and replacing them with unidirectional ones.

In CustomerConfigEntity.java:

```<code>public class CustomerConfigEntity implements Serializable {

   // ...

   @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @PrimaryKeyJoinColumn(name = "customerId", referencedColumnName = "customerId")
   private DefaultValues defaultValues;

   // ...

}
</code>```

Note that one must not use mappedBy here.

In DefaultValues.java:

```<code>   @Id
   private String customerId;
</code>```

CustomerConfigEntity has some more relationships which are all of the @OneToMany cardinality.

For those, I did the same thing but had to use @JoinColumn instead of @PrimaryKeyJoinColumn for customerId - despite the fact that the customerId is part of the primary key of the child entity. But using @PrimaryKeyJoinColumn caused JPA to create join tables, which is not what I wanted.

However, I still don't know how I would have to solve this if I really needed bi-directional relationships.

Body:
I have a problem with JPA and detached entity objects passed from outside the application via JSON deserialization.

I deserialize an object graph from JSON (passed through a HTTP POST request) and then try to update an existing entity from it.

As far as I understand JPA, using EntityManager.merge() on an object should automatically and recursively (depending on cascade) attach it and issue an UPDATE to the DB for all the objects in the tree.
However, this apparently only works well for 1) a single entity with no children or 2) the topmost entity in an object graph.

For the child entities, JPA will always issue an INSERT INTO, regardless if the object is already there, and thus run into a primary key violation.

What am I doing wrong?

The relevant part of the implementation is this:

In AdminResource.java:

@Autowire
protected CustomerConfigDAO customerConfigDao; // wrapper for the JPA persistence

@POST
@Consumes(MediaType.APPLICATION_JSON)
public void storeConfigurationData(CustomerConfigEntity config) {
    customerConfigDao.update(config); // calls EntityManager.merge(...)
}

In CustomerConfigEntity.java:

@Entity
public class CustomerConfigEntity implements Serializable {

    @Id
    private String customerID;

    @OneToOne(mappedBy = "customerConfigEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private DefaultValues defaultValues;

    /* ... snip ... */

    @PrePersist
    @PreUpdate
    public void fixBackReference() {
        if(this.defaultValues != null)
            this.defaultValues.setCustomerConfigEntity(this);
    }
}

In DefaultValues.java:

@Entity
public class DefaultValues implements Serializable {

    @Id
    @OneToOne
    @JoinColumn(name = "customerID", referencedColumnName = "cloudID")
    @JsonIgnore
    private CustomerConfigEntity customerConfigEntity;

    /* ... snip ... */

}

Someone suggested to drop the bi-directional one-to-one relationship in favour of a uni-directional one, but since customerConfigEntity is both the foreign AND the primary key in DefaultValues, removing it would require me to introduce a surrogate key. I did this by introducing an auto-incremented key, but the result was that JPA would create a new record in DEFAULTVALUES whenever a CustomerConfigEntity was saved.

Body:
I solved the problem by eliminating all the bi-directional relationships and replacing them with unidirectional ones.

In CustomerConfigEntity.java:

public class CustomerConfigEntity implements Serializable {

   // ...

   @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @PrimaryKeyJoinColumn(name = "customerId", referencedColumnName = "customerId")
   private DefaultValues defaultValues;

   // ...

}

Note that one must not use mappedBy here.

In DefaultValues.java:

   @Id
   private String customerId;

CustomerConfigEntity has some more relationships which are all of the @OneToMany cardinality.

For those, I did the same thing but had to use @JoinColumn instead of @PrimaryKeyJoinColumn for customerId - despite the fact that the customerId is part of the primary key of the child entity. But using @PrimaryKeyJoinColumn caused JPA to create join tables, which is not what I wanted.

However, I still don't know how I would have to solve this if I really needed bi-directional relationships.


问:
Does anyone know how to change or add some theme in Notepad++ x64?
I'm looking for way to change the theme in 64-bit version. I know, there is the 'themes' folder in x86. In x64 there is no one. </p>

答:
You have to add the theme plug-in(which is xml file) inside the plugin folder of the notepad ++.

So to get the theme for notepad x64 bit visit here.

https://github.com/bruderstein/npp-plugins-x64/blob/master/plugins/plugins64.xml


问:
How to reset / restart a Urho3D application scene to its initial state?
I want to reset my scene to its original state when the user presses a key, to facilitate testing or allow users to restart the game.

More precisely, how to organize my code, and what do I have to put into:

```<code>void HandleKeyDown(StringHash /*eventType*/, VariantMap& eventData) {
    using namespace KeyDown;
    int key = eventData[P_KEY].GetInt();
    if (key == KEY_R) {
        // TODO
    }
}
</code>```

to restart the application?

Here is a full runnable example, where I try to create a pong-like game:

```<code>#include <iostream>

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Object.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/IO/File.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/Urho2D/CollisionBox2D.h>
#include <Urho3D/Urho2D/CollisionCircle2D.h>
#include <Urho3D/Urho2D/ConstraintPrismatic2D.h>
#include <Urho3D/Urho2D/PhysicsEvents2D.h>
#include <Urho3D/Urho2D/PhysicsWorld2D.h>
#include <Urho3D/Urho2D/RigidBody2D.h>

using namespace Urho3D;

class Main : public Application {
    URHO3D_OBJECT(Main, Application);
public:
    Main(Context* context) : Application(context) {}
    virtual void Setup() override {
        engineParameters_[EP_FULL_SCREEN] = false;
        engineParameters_[EP_WINDOW_TITLE] = __FILE__;
        engineParameters_[EP_WINDOW_HEIGHT] = 512;
        engineParameters_[EP_WINDOW_WIDTH] = 512;
    }
    void Start() {
        auto windowHeight = this->windowWidth;
        auto wallLength = this->windowWidth;
        auto wallWidth = this->windowWidth / 20.0f;
        auto ballRadius = this->windowWidth / 20.0f;
        auto ballRestitution = 1.0f;
        auto playerLength = windowHeight / 4.0f;
        this->score = 0;
        this->steps = 0;
        this->input = this->GetSubsystem<Input>();

        // Events
        SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Main, HandleKeyDown));
        SubscribeToEvent(E_PHYSICSBEGINCONTACT2D, URHO3D_HANDLER(Main, HandlePhysicsBeginContact2D));
        SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Main, HandlePostRenderUpdate));
        SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Main, HandleUpdate));

        // Scene
        this->scene = new Scene(this->context_);
        this->scene->CreateComponent<Octree>();
        this->scene->CreateComponent<DebugRenderer>();
        this->scene->CreateComponent<PhysicsWorld2D>();
        auto physicsWorld = scene->GetComponent<PhysicsWorld2D>();
        physicsWorld->SetGravity(Vector2(0.0f, 0.0f));
        this->physicsWorld = this->scene->GetComponent<PhysicsWorld2D>();

        // Graphics
        auto cameraNode = this->scene->CreateChild("Camera");
        cameraNode->SetPosition(Vector3(windowWidth / 2.0f, windowHeight / 2.0f, -1.0f));
        auto camera = cameraNode->CreateComponent<Camera>();
        camera->SetOrthographic(true);
        camera->SetOrthoSize(windowWidth);
        auto renderer = GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_, this->scene, cameraNode->GetComponent<Camera>()));
        renderer->SetViewport(0, viewport);

        // Score
        ResourceCache *cache = this->GetSubsystem<ResourceCache>();
        auto ui = this->GetSubsystem<UI>();
        this->text = ui->GetRoot()->CreateChild<Text>();
        this->text->SetText(std::to_string(this->score).c_str());
        this->text->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
        this->text->SetHorizontalAlignment(HA_CENTER);
        this->text->SetVerticalAlignment(VA_CENTER);

        Node *wallNode;
        RigidBody2D *wallBody;
        {
            wallNode = this->scene->CreateChild("BottomWall");
            wallNode->SetPosition(Vector3(this->windowWidth / 2.0, wallWidth / 2.0f, 0.0f));
            wallBody = wallNode->CreateComponent<RigidBody2D>();
            auto box = wallNode->CreateComponent<CollisionBox2D>();
            box->SetSize(Vector2(wallLength, wallWidth));
            box->SetRestitution(0.0);
        }

        {
            auto node = wallNode->Clone();
            node->SetName("TopWall");
            node->SetPosition(Vector3(this->windowWidth / 2.0f, windowHeight - (wallWidth / 2.0f), 0.0f));
        }

        {
            auto& node = this->rightWallNode;
            node = wallNode->Clone();
            node->SetName("RightWall");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(this->windowWidth - (wallWidth / 2.0f), windowHeight / 2.0f, 0.0f));
        }

        {
            auto& node = this->leftWallNode;
            node = wallNode->Clone();
            node->SetName("LeftWall");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(-wallWidth / 2.0f, windowHeight / 2.0f, 0.0f));
        }

        {
            auto& node = this->playerNode;
            node = wallNode->Clone();
            node->SetName("Player");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(wallWidth / 2.0f, windowHeight / 2.0f, 0.0f));
            auto body = node->GetComponent<RigidBody2D>();
            body->SetBodyType(BT_DYNAMIC);
            body->SetFixedRotation(true);
            body->SetLinearDamping(4.0);
            //auto constraint = node->CreateComponent<ConstraintPrismatic2D>();
            //constraint->SetOtherBody(wallBody);
            //constraint->SetAxis(Vector2(0.0f, 1.0f));
            auto shape = node->GetComponent<CollisionBox2D>();
            shape->SetDensity(this->playerDensity);
            shape->SetFriction(1.0f);
            shape->SetRestitution(0.0);
            shape->SetSize(Vector2(playerLength, wallWidth));
        }

        {
            this->ballNode = this->scene->CreateChild("Ball");
            this->ballNode->SetPosition(Vector3(this->windowWidth / 4.0f, windowHeight / 2.0f, 0.0f));
            auto body = this->ballNode->CreateComponent<RigidBody2D>();
            body->SetBodyType(BT_DYNAMIC);
            body->SetLinearVelocity(Vector2(2 * this->windowWidth, -windowHeight / 2.0f));
            auto shape = this->ballNode->CreateComponent<CollisionCircle2D>();
            shape->SetDensity(1.0f);
            shape->SetFriction(1.0f);
            shape->SetRadius(ballRadius);
            shape->SetRestitution(ballRestitution);
        }
    }
    void Stop() {}
private:
    SharedPtr<Scene> scene;
    Node *ballNode, *playerNode, *leftWallNode, *rightWallNode;
    Text *text;
    Input *input;
    PhysicsWorld2D *physicsWorld;
    uint64_t score, steps;
    /// Larger means that the controls will react faster.
    static constexpr float playerDensity = 10.0f;
    static constexpr float windowWidth = 1.0f;
    void HandleKeyDown(StringHash /*eventType*/, VariantMap& eventData) {
        using namespace KeyDown;
        int key = eventData[P_KEY].GetInt();
        if (key == KEY_ESCAPE) {
            engine_->Exit();
        } else if (key == KEY_R) {
            this->Start();
        }
    }
    void HandlePhysicsBeginContact2D(StringHash eventType, VariantMap& eventData) {
        using namespace PhysicsBeginContact2D;
        auto nodea = static_cast<Node*>(eventData[P_NODEA].GetPtr());
        auto nodeb = static_cast<Node*>(eventData[P_NODEB].GetPtr());
        Node *otherNode;
        bool isBall = false;
        if (nodea == this->ballNode) {
            otherNode = nodeb;
            isBall = true;
        }
        if (nodeb == this->ballNode) {
            otherNode = nodea;
            isBall = true;
        }
        if (otherNode == this->rightWallNode) {
            this->score++;
        } else if (otherNode == this->leftWallNode) {
            this->score = 0;
        }
        this->text->SetText(std::to_string(this->score).c_str());
        File saveFile(this->context_, GetSubsystem<FileSystem>()->GetProgramDir() + String(this->steps) + ".xml", FILE_WRITE);
        this->scene->SaveXML(saveFile);
    }
    void HandleUpdate(StringHash eventType, VariantMap& eventData) {
        using namespace Update;
        auto timeStep = eventData[P_TIMESTEP].GetFloat();
        auto impuseMagnitude = this->windowWidth * this->playerDensity * timeStep * 10.0;
        auto body = this->playerNode->GetComponent<RigidBody2D>();
        if (this->input->GetKeyDown(KEY_DOWN)) {
            body->ApplyForceToCenter(Vector2(0.0f, -impuseMagnitude), true);
        } else if (this->input->GetKeyDown(KEY_UP)) {
            body->ApplyForceToCenter(Vector2(0.0f, impuseMagnitude), true);
        } else if (this->input->GetKeyDown(KEY_RIGHT)) {
            body->ApplyForceToCenter(Vector2(impuseMagnitude, 0.0f), true);
        } else if (input->GetKeyDown(KEY_LEFT)) {
            body->ApplyForceToCenter(Vector2(-impuseMagnitude, 0.0f), true);
        }
        this->steps++;
    }
    void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) {
        this->physicsWorld->DrawDebugGeometry();
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(Main);
</code>```

In my naive attempt, I've tried to simply call this->Start() from the callback, but it did not clear up everything: the UI still shows the old score, in addition to a new score superposed to it.

GitHub upstream: https://github.com/cirosantilli/Urho3D-cheat/blob/e58a643ccf855d659ee292aeb513e191e0c5bb95/pong.cpp

Also asked at: https://discourse.urho3d.io/t/how-to-reset-restart-a-urho3d-application-scene-to-its-initial-state/3831

答:
To empty a Scene, call Scene::Clear() on it. This removes all the Scene's Components and child Nodes. After this you can call a function that rebuilds the scene.

Alternately you could create a custom reset event that all Objects that require some form of resetting subscribe their HandleReset methods to. To restart the game you would then call SendEvent(E_RESET).

Body:
I want to reset my scene to its original state when the user presses a key, to facilitate testing or allow users to restart the game.

More precisely, how to organize my code, and what do I have to put into:

void HandleKeyDown(StringHash /*eventType*/, VariantMap& eventData) {
    using namespace KeyDown;
    int key = eventData[P_KEY].GetInt();
    if (key == KEY_R) {
        // TODO
    }
}

to restart the application?

Here is a full runnable example, where I try to create a pong-like game:

#include <iostream>

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Object.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/IO/File.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/Urho2D/CollisionBox2D.h>
#include <Urho3D/Urho2D/CollisionCircle2D.h>
#include <Urho3D/Urho2D/ConstraintPrismatic2D.h>
#include <Urho3D/Urho2D/PhysicsEvents2D.h>
#include <Urho3D/Urho2D/PhysicsWorld2D.h>
#include <Urho3D/Urho2D/RigidBody2D.h>

using namespace Urho3D;

class Main : public Application {
    URHO3D_OBJECT(Main, Application);
public:
    Main(Context* context) : Application(context) {}
    virtual void Setup() override {
        engineParameters_[EP_FULL_SCREEN] = false;
        engineParameters_[EP_WINDOW_TITLE] = __FILE__;
        engineParameters_[EP_WINDOW_HEIGHT] = 512;
        engineParameters_[EP_WINDOW_WIDTH] = 512;
    }
    void Start() {
        auto windowHeight = this->windowWidth;
        auto wallLength = this->windowWidth;
        auto wallWidth = this->windowWidth / 20.0f;
        auto ballRadius = this->windowWidth / 20.0f;
        auto ballRestitution = 1.0f;
        auto playerLength = windowHeight / 4.0f;
        this->score = 0;
        this->steps = 0;
        this->input = this->GetSubsystem<Input>();

        // Events
        SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Main, HandleKeyDown));
        SubscribeToEvent(E_PHYSICSBEGINCONTACT2D, URHO3D_HANDLER(Main, HandlePhysicsBeginContact2D));
        SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Main, HandlePostRenderUpdate));
        SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Main, HandleUpdate));

        // Scene
        this->scene = new Scene(this->context_);
        this->scene->CreateComponent<Octree>();
        this->scene->CreateComponent<DebugRenderer>();
        this->scene->CreateComponent<PhysicsWorld2D>();
        auto physicsWorld = scene->GetComponent<PhysicsWorld2D>();
        physicsWorld->SetGravity(Vector2(0.0f, 0.0f));
        this->physicsWorld = this->scene->GetComponent<PhysicsWorld2D>();

        // Graphics
        auto cameraNode = this->scene->CreateChild("Camera");
        cameraNode->SetPosition(Vector3(windowWidth / 2.0f, windowHeight / 2.0f, -1.0f));
        auto camera = cameraNode->CreateComponent<Camera>();
        camera->SetOrthographic(true);
        camera->SetOrthoSize(windowWidth);
        auto renderer = GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_, this->scene, cameraNode->GetComponent<Camera>()));
        renderer->SetViewport(0, viewport);

        // Score
        ResourceCache *cache = this->GetSubsystem<ResourceCache>();
        auto ui = this->GetSubsystem<UI>();
        this->text = ui->GetRoot()->CreateChild<Text>();
        this->text->SetText(std::to_string(this->score).c_str());
        this->text->SetFont(cache->GetResource("Fonts/Anonymous Pro.ttf"), 15);
        this->text->SetHorizontalAlignment(HA_CENTER);
        this->text->SetVerticalAlignment(VA_CENTER);

        Node *wallNode;
        RigidBody2D *wallBody;
        {
            wallNode = this->scene->CreateChild("BottomWall");
            wallNode->SetPosition(Vector3(this->windowWidth / 2.0, wallWidth / 2.0f, 0.0f));
            wallBody = wallNode->CreateComponent<RigidBody2D>();
            auto box = wallNode->CreateComponent<CollisionBox2D>();
            box->SetSize(Vector2(wallLength, wallWidth));
            box->SetRestitution(0.0);
        }

        {
            auto node = wallNode->Clone();
            node->SetName("TopWall");
            node->SetPosition(Vector3(this->windowWidth / 2.0f, windowHeight - (wallWidth / 2.0f), 0.0f));
        }

        {
            auto& node = this->rightWallNode;
            node = wallNode->Clone();
            node->SetName("RightWall");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(this->windowWidth - (wallWidth / 2.0f), windowHeight / 2.0f, 0.0f));
        }

        {
            auto& node = this->leftWallNode;
            node = wallNode->Clone();
            node->SetName("LeftWall");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(-wallWidth / 2.0f, windowHeight / 2.0f, 0.0f));
        }

        {
            auto& node = this->playerNode;
            node = wallNode->Clone();
            node->SetName("Player");
            node->SetRotation(Quaternion(0.0f, 0.0f, 90.0f));
            node->SetPosition(Vector3(wallWidth / 2.0f, windowHeight / 2.0f, 0.0f));
            auto body = node->GetComponent<RigidBody2D>();
            body->SetBodyType(BT_DYNAMIC);
            body->SetFixedRotation(true);
            body->SetLinearDamping(4.0);
            //auto constraint = node->CreateComponent<ConstraintPrismatic2D>();
            //constraint->SetOtherBody(wallBody);
            //constraint->SetAxis(Vector2(0.0f, 1.0f));
            auto shape = node->GetComponent<CollisionBox2D>();
            shape->SetDensity(this->playerDensity);
            shape->SetFriction(1.0f);
            shape->SetRestitution(0.0);
            shape->SetSize(Vector2(playerLength, wallWidth));
        }

        {
            this->ballNode = this->scene->CreateChild("Ball");
            this->ballNode->SetPosition(Vector3(this->windowWidth / 4.0f, windowHeight / 2.0f, 0.0f));
            auto body = this->ballNode->CreateComponent<RigidBody2D>();
            body->SetBodyType(BT_DYNAMIC);
            body->SetLinearVelocity(Vector2(2 * this->windowWidth, -windowHeight / 2.0f));
            auto shape = this->ballNode->CreateComponent<CollisionCircle2D>();
            shape->SetDensity(1.0f);
            shape->SetFriction(1.0f);
            shape->SetRadius(ballRadius);
            shape->SetRestitution(ballRestitution);
        }
    }
    void Stop() {}
private:
    SharedPtr<Scene> scene;
    Node *ballNode, *playerNode, *leftWallNode, *rightWallNode;
    Text *text;
    Input *input;
    PhysicsWorld2D *physicsWorld;
    uint64_t score, steps;
    /// Larger means that the controls will react faster.
    static constexpr float playerDensity = 10.0f;
    static constexpr float windowWidth = 1.0f;
    void HandleKeyDown(StringHash /*eventType*/, VariantMap& eventData) {
        using namespace KeyDown;
        int key = eventData[P_KEY].GetInt();
        if (key == KEY_ESCAPE) {
            engine_->Exit();
        } else if (key == KEY_R) {
            this->Start();
        }
    }
    void HandlePhysicsBeginContact2D(StringHash eventType, VariantMap& eventData) {
        using namespace PhysicsBeginContact2D;
        auto nodea = static_cast<Node*>(eventData[P_NODEA].GetPtr());
        auto nodeb = static_cast<Node*>(eventData[P_NODEB].GetPtr());
        Node *otherNode;
        bool isBall = false;
        if (nodea == this->ballNode) {
            otherNode = nodeb;
            isBall = true;
        }
        if (nodeb == this->ballNode) {
            otherNode = nodea;
            isBall = true;
        }
        if (otherNode == this->rightWallNode) {
            this->score++;
        } else if (otherNode == this->leftWallNode) {
            this->score = 0;
        }
        this->text->SetText(std::to_string(this->score).c_str());
        File saveFile(this->context_, GetSubsystem<FileSystem>()->GetProgramDir() + String(this->steps) + ".xml", FILE_WRITE);
        this->scene->SaveXML(saveFile);
    }
    void HandleUpdate(StringHash eventType, VariantMap& eventData) {
        using namespace Update;
        auto timeStep = eventData[P_TIMESTEP].GetFloat();
        auto impuseMagnitude = this->windowWidth * this->playerDensity * timeStep * 10.0;
        auto body = this->playerNode->GetComponent<RigidBody2D>();
        if (this->input->GetKeyDown(KEY_DOWN)) {
            body->ApplyForceToCenter(Vector2(0.0f, -impuseMagnitude), true);
        } else if (this->input->GetKeyDown(KEY_UP)) {
            body->ApplyForceToCenter(Vector2(0.0f, impuseMagnitude), true);
        } else if (this->input->GetKeyDown(KEY_RIGHT)) {
            body->ApplyForceToCenter(Vector2(impuseMagnitude, 0.0f), true);
        } else if (input->GetKeyDown(KEY_LEFT)) {
            body->ApplyForceToCenter(Vector2(-impuseMagnitude, 0.0f), true);
        }
        this->steps++;
    }
    void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) {
        this->physicsWorld->DrawDebugGeometry();
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(Main);

In my naive attempt, I've tried to simply call this->Start() from the callback, but it did not clear up everything: the UI still shows the old score, in addition to a new score superposed to it.

GitHub upstream: https://github.com/cirosantilli/Urho3D-cheat/blob/e58a643ccf855d659ee292aeb513e191e0c5bb95/pong.cpp

Also asked at: https://discourse.urho3d.io/t/how-to-reset-restart-a-urho3d-application-scene-to-its-initial-state/3831