问:
How to set post tags by some meta keys?
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

```<code><?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>
</code>```

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

```<code><?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>
</code>```

Then, all tag is eliminatd.

答:
Hope this help you.</p>

```<code>    global $post;
    $post_id = $post->ID;
    $array_tags_and_ids = [
        $post_id => ["aaaaa", "bbbbb", "ccccc"]
    ];
    foreach ($array_tags_and_ids as $key => $value) {
        // re-call the value and get only the text value
        $implode_tags_names = implode( ', ', $value );

        // wordpress function
        wp_set_post_tags( $key, $implode_tags_names, true );
}
</code>```

Title: How to set post tags by some meta keys?

Body:
I prepared following code to overwrite post tags following several meta keys.
Now, it works for only one meta key.  How can I apply it to several meta keys?

<?php
global $post;
$post_id = $post->ID;
$tags[] = get_post_meta($post_id, 'aaaaa', $single);
$tags[] = get_post_meta($post_id, 'bbbbb', $single);
$tags[] = get_post_meta($post_id, 'ccccc', $single);
$tags = array_unique( array_filter( $tags ) ); // here, adding array_filter to remove empty get_post_meta results
wp_set_post_tags( $post_id, $tags, false );
?>

By above code, meta value of meta key aaaaa only applied as post tag, and meta value of meta key bbbbb and ccccc is ignored.

After I hear advise below, I tried this code too.

<?php
global $post;
$post_id = $post->ID;

$tags = get_post_meta($post_id, 'aaaaa', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'bbbbb', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

$tags = get_post_meta($post_id, 'ccccc', $single);
if (!empty($tag) ) { wp_add_post_tags( $post_id, $$tag ); }

wp_set_post_tags( $post_id, $tags, false );

?>

Then, all tag is eliminatd.

Body:
Hope this help you.

    global $post;
    $post_id = $post->ID;
    $array_tags_and_ids = [
        $post_id => ["aaaaa", "bbbbb", "ccccc"]
    ];
    foreach ($array_tags_and_ids as $key => $value) {
        // re-call the value and get only the text value
        $implode_tags_names = implode( ', ', $value );

        // wordpress function
        wp_set_post_tags( $key, $implode_tags_names, true );
}


来源: stackexchange

问:
Multithreaded object loading while rendering with OpenGL
I want to load some textures and meshes in a separate thread while the main program is showing a loading screen because it takes a few seconds to load all resources. I'm using OpenGL and GLFW. I tried to accomplish this with the following code:

```<code>    void *status;

    if(pthread_create(&loader, NULL, &loader_func, NULL))
    {
        fprintf(stderr, "Error creating loader thread\n");
        return 1;
    }

    while(_flags & FLAG_LOADING)
    {
        vec3 color = { 0.1, 0.3, 1.0 };
        if(glfwWindowShouldClose(window))
        {
            resource_destroy();
            glfwTerminate();
            return 0;
        }

        GL_CHECK(glClearColor(0.1, 0.1, 0.1, 1.0));
        GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

        font_renderer_activate();
        render_string(&_font_menu, "Loading...", _width / 2, _height / 2, 64,
                color, ALIGN_V_CENTER | ALIGN_H_CENTER);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    if(pthread_join(loader, &status))
    {
        fprintf(stderr, "Error joining loader and main thread\n");
        return 1;
    }

    if(*(int *)status)
    {
        fprintf(stderr, "Error loading resources\n");
        return 1;
    }
</code>```

loader_func() is not rendering to the screen, and only uses OpenGL functions for creating VAOs, VBOs etc. and loading data into them.

The problem is that after the loading text shows up on screen and loading has finished, nothing shows up on screen (EDIT: except the textual HUD) and I'm getting a lot of debug error messages in my log (I'm wrapping all OpenGL calls in a macro that checks for errors with glGetError):

```<code>main.c:588
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap_texture);
GL_Error 0x502: GL_INVALID_OPERATION
main.c:589
glDrawArrays(GL_TRIANGLES, OFFSET_SKYBOX, VERTICES_SKYBOX);
GL_Error 0x502: GL_INVALID_OPERATION
main.c:629
glDrawArrays(GL_TRIANGLES, OFFSET_SELECTOR, VERTICES_SELECTOR);
GL_Error 0x502: GL_INVALID_OPERATION
</code>```

When I call loader_func directly, there are no errors and the main render loop works correctly.

I read that to use OpenGL functions in another thread it is required to call glfwMakeContextCurrent but that wouldn't work in my case, because then the loading screen wouldn't be rendered. My only idea was to utilize a second library like SDL to create a window while loading, then destroy it and create a new window with GLFW for use with OpenGL. Is that what I want to achieve possible with just OpenGL?

答:
The easiest way to handle this is to have the main thread create and manage all of the OpenGL objects, while the loading thread does the File IO (easily the slowest part of the loading). Once the loading thread is finished with loading a particular asset, it can deliver the loaded data to the main thread via <insert your favorite thread-safe mechanism here>, which can do the final OpenGL uploading part.

After all, it's not like rendering a loading screen is a huge performance drain or something, so the cost of uploading on the main thread will be minimal. This also permits you to do that loading bar thing, since your main thread will frequently be getting the results of the loading process, so it knows at any time how much of the loading is finished.

If you absolutely must have two threads both making OpenGL calls for some reason, then you should also have two OpenGL contexts, each being current in a different thread, and the two contexts sharing objects with each other. GLFW is perfectly happy to provide this if you ask it nicely. Create your main window as normal, then set the GLFW_VISIBLE hint to GLFW_FALSE, and create a second window (with an arbitrary resolution). You should pass the main window as the last parameter to glfwCreateWindow, so that the two contexts can share objects. You can then set each window current in different contexts and you're fine.

One word of caution. Contexts that share objects between them only share certain objects. Objects which reference other objects cannot be shared (also query objects are unsharable for some reason). VAOs reference buffer objects, so they can't be shared. So there's no point in trying to create them on the off-screen context.

ContentLicense: CC BY-SA 4.0

Body:
I want to load some textures and meshes in a separate thread while the main program is showing a loading screen because it takes a few seconds to load all resources. I'm using OpenGL and GLFW. I tried to accomplish this with the following code:

    void *status;

    if(pthread_create(&loader, NULL, &loader_func, NULL))
    {
        fprintf(stderr, "Error creating loader thread\n");
        return 1;
    }

    while(_flags & FLAG_LOADING)
    {
        vec3 color = { 0.1, 0.3, 1.0 };
        if(glfwWindowShouldClose(window))
        {
            resource_destroy();
            glfwTerminate();
            return 0;
        }

        GL_CHECK(glClearColor(0.1, 0.1, 0.1, 1.0));
        GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

        font_renderer_activate();
        render_string(&_font_menu, "Loading...", _width / 2, _height / 2, 64,
                color, ALIGN_V_CENTER | ALIGN_H_CENTER);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    if(pthread_join(loader, &status))
    {
        fprintf(stderr, "Error joining loader and main thread\n");
        return 1;
    }

    if(*(int *)status)
    {
        fprintf(stderr, "Error loading resources\n");
        return 1;
    }

loader_func() is not rendering to the screen, and only uses OpenGL functions for creating VAOs, VBOs etc. and loading data into them.

The problem is that after the loading text shows up on screen and loading has finished, nothing shows up on screen (EDIT: except the textual HUD) and I'm getting a lot of debug error messages in my log (I'm wrapping all OpenGL calls in a macro that checks for errors with glGetError):

main.c:588
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap_texture);
GL_Error 0x502: GL_INVALID_OPERATION
main.c:589
glDrawArrays(GL_TRIANGLES, OFFSET_SKYBOX, VERTICES_SKYBOX);
GL_Error 0x502: GL_INVALID_OPERATION
main.c:629
glDrawArrays(GL_TRIANGLES, OFFSET_SELECTOR, VERTICES_SELECTOR);
GL_Error 0x502: GL_INVALID_OPERATION

When I call loader_func directly, there are no errors and the main render loop works correctly.

I read that to use OpenGL functions in another thread it is required to call glfwMakeContextCurrent but that wouldn't work in my case, because then the loading screen wouldn't be rendered. My only idea was to utilize a second library like SDL to create a window while loading, then destroy it and create a new window with GLFW for use with OpenGL. Is that what I want to achieve possible with just OpenGL?


问:
Break if input left blank inside of an if statement
I have a school assignment for Python in which I have a backpack of items and need to make code to ask the user if they want to: a) add an item to the backpack, b) check the items in the backpack, and c) quit the program.

For my code, I want to make it so that if the user at input for adding a new item just hits return and leaves the input blank, it will re-prompt to the input again rather than continuing the code if no item is actually added. Here's what I have so far:

```<code>import sys

itemsInBackpack = ["book", "computer", "keys", "travel mug"]

while True:
    print("Would you like to:")
    print("1. Add an item to the backpack?")
    print("2. Check if an item is in the backpack?")
    print("3. Quit")
    userChoice = input()

    if (userChoice == "1"):
        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        if itemAddNew == "":
            break
        else:
            itemsInBackpack.insert(0, itemAddNew)
            print("Added to backpack.")
</code>```

With my code here, even if I hit return in a test and leave the input blank, the code still continues onward and doesn't break to re-prompt input again. Is it because I'm using an if statement inside of an if statement already? I'm sure in general there's a better way to do this, but as a beginner I'm stumped and could use a shove in the right direction.

答:
The break stops everything in your loop and causes your program to end.

If you want to prompt for input until the user gives you something, change this:

```<code>        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        if itemAddNew == "":
            break
</code>```

to this:

```<code>        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        while itemAddNew == "":
            #Added some output text to tell the user what went wrong.
            itemAddNew = input("You didn't enter anything. Try again.\n")
</code>```

This will keep going WHILE the text is empty.

Body:
I have a school assignment for Python in which I have a backpack of items and need to make code to ask the user if they want to: a) add an item to the backpack, b) check the items in the backpack, and c) quit the program.

For my code, I want to make it so that if the user at input for adding a new item just hits return and leaves the input blank, it will re-prompt to the input again rather than continuing the code if no item is actually added. Here's what I have so far:

import sys

itemsInBackpack = ["book", "computer", "keys", "travel mug"]

while True:
    print("Would you like to:")
    print("1. Add an item to the backpack?")
    print("2. Check if an item is in the backpack?")
    print("3. Quit")
    userChoice = input()

    if (userChoice == "1"):
        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        if itemAddNew == "":
            break
        else:
            itemsInBackpack.insert(0, itemAddNew)
            print("Added to backpack.")

With my code here, even if I hit return in a test and leave the input blank, the code still continues onward and doesn't break to re-prompt input again. Is it because I'm using an if statement inside of an if statement already? I'm sure in general there's a better way to do this, but as a beginner I'm stumped and could use a shove in the right direction.

Body:
The break stops everything in your loop and causes your program to end.

If you want to prompt for input until the user gives you something, change this:

        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        if itemAddNew == "":
            break

to this:

        print("What item do you want to add to the backpack?")
        itemAddNew = input()
        while itemAddNew == "":
            #Added some output text to tell the user what went wrong.
            itemAddNew = input("You didn't enter anything. Try again.\n")

This will keep going WHILE the text is empty.


问:
Firebase Hosting - function rewrite pricing
If you use Firebase Hosting to direct requests to a Cloud Function via a rewrite, does that request traffic that "passes through" hosting get billed into Firebase Hosting GB transferred? (Ignoring the billing for the Cloud Function)

In other words,

Do Firebase Hosting function rewrites themselves cost money when requests come in?

To be clear,

Obviously, HTTP Cloud Functions cost money and have quotas. But, HTTP Cloud Function billing aside, does the traffic (ie the bytes) passing through the Firebase Hosting Rewrite get billed into Firebase Hosting billing?

To limit the scope of answers, the answer is either A or B:

A. $ for the function + $ for the request bytes passing through hosting.

OR

B. $ for the function + the rewrite doesn't cost anything.

答:
UPDATE:

The official answer is A.

I was shocked to discover this, so then I asked about other assumptions I had. I also found out that,

If Firebase Hosting has a rewrite to a function that is secured with IAM, then even the unauthorized requests are billed on GB Transferred when the function returns an "unauthorized" response. Even when the function itself is not billed for unauthorized requests.

If a function rewrite or file does not exist at a certain route, then you are billed on GB Transferred when Firebase Hosting sends a "Resource Not Found" response. Yes, sending the characters in a "Resource Not Found" response that you didn't implement is billed.

Quotes directly from official Firebase Support:

My Question:

"Does Firebase Hosting bill when sending the "Page Not Found"
page when a resource is not found? I would have assumed the answer is
an obvious no for that case, but since unauthorized cloud function
invocations are billed, I don't want to assume anything."

Support Answer:

"Regarding the 'Page not Found', I've confirmed with the (Google Firebase) team that it is being billed/allocated to GB transferred/downloads."

"Regarding your original question, Firebase Hosting bills for the
bytes that get served to end users. In the case of Cloud Functions, it
does not matter whether it's a success or not."

"Yes, you will be charged both for Cloud Functions invocation, and
Firebase Hosting data transferred to. However, if you cache the
content in Firebase Hosting, cache hits are not charged to Cloud
Functions."


问:
Add suffix to file name before extension
What's the simplest way to add a suffix to a file name before the extension in Objective-C?

Example

Original name: image.png

Suffix: ~ipad

Result: image~ipad.png

答:
Using URL methods:

let suffixedFileURL = fileURL
    .deletingLastPathComponent()
    .appendingPathComponent(
        fileURL
            .deletingPathExtension()
            .lastPathComponent
            .appending("suffix")
    )
    .appendingPathExtension(fileURL.pathExtension)
```

ContentLicense: CC BY-SA 2.5


问:
How to prevent wrong values in an initializer list?
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

```<code>class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};
</code>```

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

```<code>class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};
</code>```

答:
There are three major ways:

Chain the validation with the comma-operator:

```<code>a(int c) : b(validate(c), c) {}
</code>```

Remember that the initializers are executed strictly depth-first, in declaration order, ignoring virtual inheritance.

Using the ternary operator:

```<code>a(int c) : b(validate(c) ? c : throw 0) {}
</code>```

This needs the least amount of folderol if it's really a one-off.

Using a transforming and validating class or function:

```<code>a(int c) : b(process(c)) {}
</code>```

Optionally, they might be combined with ctor-chaining, especially if more than one result comes from processing the inputs:

```<code>private:
    struct process {
        ...
    };
    a(process x) : b(x.b), c(x.c), d(x.d) {}
public:
a(int c) : a(process(c)) {}
</code>```

Body:
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};

Body:
There are three major ways:

Chain the validation with the comma-operator:

a(int c) : b(validate(c), c) {}

Remember that the initializers are executed strictly depth-first, in declaration order, ignoring virtual inheritance.

Using the ternary operator:

a(int c) : b(validate(c) ? c : throw 0) {}

This needs the least amount of folderol if it's really a one-off.

Using a transforming and validating class or function:

a(int c) : b(process(c)) {}

Optionally, they might be combined with ctor-chaining, especially if more than one result comes from processing the inputs:

private:
    struct process {
        ...
    };
    a(process x) : b(x.b), c(x.c), d(x.d) {}
public:
a(int c) : a(process(c)) {}


问:
the closest Sunday before given date with JavaScript
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

```<code>give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
</code>```

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

答:
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:

```<code><script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)

var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was "  + r);

</script>
</code>```

So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful

http://www.w3schools.com/js/js_obj_date.asp

http://www.w3schools.com/jsref/jsref_setFullYear.asp

http://www.w3schools.com/jsref/jsref_getMonth.asp

(You can probably find the other functions that you need)

I hope this helps a bit even though it is not a complete answer.

ContentLicense: CC BY-SA 3.0

Body:
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

Body:
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:

<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)

var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was "  + r);

</script>

So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful

http://www.w3schools.com/js/js_obj_date.asp

http://www.w3schools.com/jsref/jsref_setFullYear.asp

http://www.w3schools.com/jsref/jsref_getMonth.asp

(You can probably find the other functions that you need)

I hope this helps a bit even though it is not a complete answer.


问:
How to return value from a stage before closing it?
I have a "main stage" where I press a button to open a "second stage" where I have a table, the user selects one item of the the table and click on "asignar" button (which is just a confirm button), once clicked, it must return the code of the item selected in the table to the main stage and close the second stage.

Here is the code that matters.

I have an INT variable which must take the value of a function:

```<code>codigo = controller.setVista(this, usuario, password);
</code>```

The "setVista" function goes like this:

```<code>public int setVista(ListHorarios vista, String usuario, String password) {
this.vista = vista;
this.usuario = usuario;
this.password = password;
this.inicializarTabla();
this.actualizarTabla(0, "%");

btnSeleccionar.setOnAction(e -> {
    asignarSeleccion();
    Stage stage = (Stage) btnSeleccionar.getScene().getWindow();
    stage.close();
});
    return codigo_horario;
}
</code>```

And the "asignarSeleccion" like this:

```<code>private void asignarSeleccion() {
    final HorarioTableModelo aux_horario = getTablaSeleccionada();
    posicion = datos.indexOf(aux_horario);
    if (aux_horario != null) {
        codigo_horario = aux_horario.getCodigo();
    }
}
</code>```

My problem is that I can't get the "codigo_horario" value into the first variable "codigo" before the stage closes, what do I am missing?

答:
There is some error in 4baad4's example. If the method in the controller is iCanGetDataBeforeClose, then that's what should be called:

```<code>String someValue = controller.iCanGetDataBeforeClose();
</code>```

But even that didn't work right for me.  I actually got this to work without using setOnCloseRequest at all.  In the form controller, I had a method like this:

```<code>public boolean getCompleted() {
    return this.finished;
}
</code>```

Then in the form calling it:

```<code>FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("myView.fxml"));
AnchorPane pane = (AnchorPane) loader.load();
myViewController controller = loader.getController();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
stage.showAndWait();
if (controller.getCompleted()){
    doStuff();
}
</code>```

One might think that since the stage had exited that the controller would throw a null reference exception, but it didn't, and it returned the correct response.

This solution works and is simplest proposed IMHO.

Body:
I have a "main stage" where I press a button to open a "second stage" where I have a table, the user selects one item of the the table and click on "asignar" button (which is just a confirm button), once clicked, it must return the code of the item selected in the table to the main stage and close the second stage.

Here is the code that matters.

I have an INT variable which must take the value of a function:

codigo = controller.setVista(this, usuario, password);

The "setVista" function goes like this:

public int setVista(ListHorarios vista, String usuario, String password) {
this.vista = vista;
this.usuario = usuario;
this.password = password;
this.inicializarTabla();
this.actualizarTabla(0, "%");

btnSeleccionar.setOnAction(e -> {
    asignarSeleccion();
    Stage stage = (Stage) btnSeleccionar.getScene().getWindow();
    stage.close();
});
    return codigo_horario;
}

And the "asignarSeleccion" like this:

private void asignarSeleccion() {
    final HorarioTableModelo aux_horario = getTablaSeleccionada();
    posicion = datos.indexOf(aux_horario);
    if (aux_horario != null) {
        codigo_horario = aux_horario.getCodigo();
    }
}

My problem is that I can't get the "codigo_horario" value into the first variable "codigo" before the stage closes, what do I am missing?

Body:
There is some error in 4baad4's example. If the method in the controller is iCanGetDataBeforeClose, then that's what should be called:

String someValue = controller.iCanGetDataBeforeClose();

But even that didn't work right for me.  I actually got this to work without using setOnCloseRequest at all.  In the form controller, I had a method like this:

public boolean getCompleted() {
    return this.finished;
}

Then in the form calling it:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("myView.fxml"));
AnchorPane pane = (AnchorPane) loader.load();
myViewController controller = loader.getController();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
stage.showAndWait();
if (controller.getCompleted()){
    doStuff();
}

One might think that since the stage had exited that the controller would throw a null reference exception, but it didn't, and it returned the correct response.

This solution works and is simplest proposed IMHO.


问:
In the python datetime why is the first month, 'January', = 1, but 'Monday', the first day of the week = 0?
I was just learning about the datetime module, and noticed that when you use .month it provides the month in a range of 1 to 12, where 1 is January. When using .weekday, however, it provides the weekday in a range of 0 to 6.

Most list indexes start at 0, so why wouldn't January, from the list of months also be 0, not 1? I looked at the python datetime docs, but didn't see an explanation. Thanks in advance.

答:
In different parts of the world different calendars are followed : Gregorian Calendar, Julian Calendar, Vedic Calendar and so on.

1) Months are generally numbered from 1 to 12(I have not seen anyone associating January with 0. There could be exceptions which I am not aware of). That leads me to focus on the second point - i:e numbering of weekdays.

2) Weekdays are numbered differently in different parts of the world. Some associate Monday with 0 and some with 1. For that matter, Date formats are represented differently in North America, Europe and in other places or in different types of calendars. This causes confusion.

To address the problem mentioned in #2 the International Organization for Standardization (ISO) came up with a date format to express a numeric calendar date in standardised way to eliminate ambiguity. Part of the world considers Monday to be associated with number 0 and others with 1.
As per Gregorian calendar wikipedia page(please check the hyperlink mentioned below): "Opinions vary about the numbering of the days of the week. ISO 8601, in common use worldwide, starts with Monday=1"

Now speaking of python: I have not read/ known what did make the writer of weekday() method to have return 0 for Monday and 6 for Sunday. But then the other option is there which is more standardised. i:e

isoweekday(): Returns integer 1 for Monday and 7 for Sunday. This follows the ISO format - hence such numbering.

So I assume, the author created a method for everyone and that makes the usage more flexible and more specific at the same time.

Below snippet of code shows both the methods:

```<code>import datetime as dt
td = dt.datetime(2020,2,17) # checking for 17 Feb 2020
print ("This is weekday() method -->",td.weekday(),"--->", dt.datetime.strftime(td,'%a'))
print ("This is isoweekday() method -->",td.isoweekday(),"--->", dt.datetime.strftime(td,'%a'))
</code>```

Output:

```<code>This is weekday() method --> 0 ---> Mon
This is isoweekday() method --> 1 ---> Mon
</code>```

for further reading on calendar algorithms / types you may check these links:
ISO_week_date, Determination_of_the_day_of_the_week, Gregorian_calendar, isoweekday

Body:
In different parts of the world different calendars are followed : Gregorian Calendar, Julian Calendar, Vedic Calendar and so on.

1) Months are generally numbered from 1 to 12(I have not seen anyone associating January with 0. There could be exceptions which I am not aware of). That leads me to focus on the second point - i:e numbering of weekdays.

2) Weekdays are numbered differently in different parts of the world. Some associate Monday with 0 and some with 1. For that matter, Date formats are represented differently in North America, Europe and in other places or in different types of calendars. This causes confusion.

To address the problem mentioned in #2 the International Organization for Standardization (ISO) came up with a date format to express a numeric calendar date in standardised way to eliminate ambiguity. Part of the world considers Monday to be associated with number 0 and others with 1.
As per Gregorian calendar wikipedia page(please check the hyperlink mentioned below): "Opinions vary about the numbering of the days of the week. ISO 8601, in common use worldwide, starts with Monday=1"

Now speaking of python: I have not read/ known what did make the writer of weekday() method to have return 0 for Monday and 6 for Sunday. But then the other option is there which is more standardised. i:e

isoweekday(): Returns integer 1 for Monday and 7 for Sunday. This follows the ISO format - hence such numbering.

So I assume, the author created a method for everyone and that makes the usage more flexible and more specific at the same time.

Below snippet of code shows both the methods:

import datetime as dt
td = dt.datetime(2020,2,17) # checking for 17 Feb 2020
print ("This is weekday() method -->",td.weekday(),"--->", dt.datetime.strftime(td,'%a'))
print ("This is isoweekday() method -->",td.isoweekday(),"--->", dt.datetime.strftime(td,'%a'))

Output:

This is weekday() method --> 0 ---> Mon
This is isoweekday() method --> 1 ---> Mon

for further reading on calendar algorithms / types you may check these links:
ISO_week_date, Determination_of_the_day_of_the_week, Gregorian_calendar, isoweekday


问:
Overlapping multi-parameter instances and instance specificity
```<code>{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module OverlappingSpecificsError where

class EqM a b where
    (===) :: a -> b -> Bool

instance {-# OVERLAPPABLE #-} Eq a => EqM a a where
    a === b = a == b

instance {-# OVERLAPPABLE #-} EqM a b where
    a === b = False

aretheyreallyeq :: (Eq a, Eq b) => Either a b -> Either a b -> Bool
aretheyreallyeq (Left a1) (Right b2) = a1 == b2

aretheyeq :: (Eq a, Eq b) => Either a b -> Either a b -> Bool
aretheyeq (Left a1) (Right b2) = a1 === b2
</code>```

Neither aretheyreallyeq or aretheyeq compile, but the error for aretheyreallyeq makes sense to me, and also tells me that aretheyeq should not give an error: One of the instances that GHCi suggests are possible for EqM in aretheyeq should be impossible due to the same error on aretheyreallyeq. What's going on?

The point is, GHCi insists that both of the instances of EqM are applicable in aretheyeq. But a1 is of type a and b2 is of type b, so in order for the first instance to be applicable, it would have to have the types a and b unify.

But this should not be possible, since they are declared as type variables at the function signature (that is, using the first EqM instance would give rise to the function being of type Either a a -> Either a a -> Bool, and the error in aretheyreallyeq tells me that GHCi will not allow that (which is what I expected anyway).

Am I missing something, or is this a bug in how overlapping instances with multi-parameter type classes are checked?

I am thinking maybe it has to do with the fact that a and b could be further instantiated later on to the point where they are equal, outside aretheyeq, and then the first instance would be valid? But the same is true for aretheyreallyeq. The only difference is that if they do not ever unify we have an option for aretheyeq, but we do not for aretheyreallyeq. In any case, Haskell does not have dynamic dispatch for plenty of good and obvious reasons, so what is the fear in committing to the instance that will always work regardless of whether later on a and b are unifiable? Maybe there is some way to present this that would make choosing the instance when calling the function possible in some way?

It is worth noting that if I remove the second instance, then the function obviously still does not compile, stating that no instance EqM a b can be found. So if I do not have that instance, then none works, but when that one works, suddenly the other does too and I have an overlap? Smells like bug to me miles away.

答:
To further complete Alexey's answer, which really gave me the hint at what I should do to achieve the behaviour I wanted, I compiled the following minimum working example of a slightly different situation more alike my real use case (which has to do with ExistentialQuantification):

```<code>{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
module ExistentialTest where

class Class1 a b where
    foo :: a -> b

instance {-# INCOHERENT #-} Monoid a => Class1 a (Either b a) where
    foo x = Right (x <> x)

instance {-# INCOHERENT #-} Monoid a => Class1 a (Either a b) where
    foo x = Left x

data Bar a = Dir a | forall b. Class1 b a => FromB b

getA :: Bar a -> a
getA (Dir a) = a
getA (FromB b) = foo b

createBar :: Bar (Either String t)
createBar = FromB "abc"

createBar2 :: Bar (Either t String)
createBar2 = FromB "def"
</code>```

If you remove the {-# INCOHERENT #-} annotations, you get exactly the same compile errors as in my original example on both createBar and createBar2, and the point is the same: in createBar it is clear that the only suitable instance is the second one, whereas in createBar2 the only suitable one is the first one, but Haskell refuses to compile because of this apparent confusion it might create when using it, until you annotate them with INCOHERENT.

And then, the code works exactly as you'd expect it to: getA createBar returns Left "abc" whereas getA createBar2 returns Right "defdef", which is exactly the only thing that could happen in a sensible type system.

So, my conclusion is: the INCOHERENT annotation is precisely to allow what I wanted to do since the beginning without Haskell complaining about potentially confusing instances and indeed taking the only one that makes sense. A doubt remains as to whether INCOHERENT may make it so that instances that indeed remain overlapping even after taking into account everything compile, using an arbitrary one (which is obviously bad and dangerous). So, a corollary to my conclusion is: only use INCOHERENT when you absolutely need to and are absolutely convinced that there is indeed only one valid instance.

I still think it is a bit absurd that Haskell has no more natural and safe way to tell the compiler to stop worrying about me being potentially being confused and doing what is obviously the only type checking answer to the problem...

Body:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module OverlappingSpecificsError where

class EqM a b where
    (===) :: a -> b -> Bool

instance {-# OVERLAPPABLE #-} Eq a => EqM a a where
    a === b = a == b

instance {-# OVERLAPPABLE #-} EqM a b where
    a === b = False

aretheyreallyeq :: (Eq a, Eq b) => Either a b -> Either a b -> Bool
aretheyreallyeq (Left a1) (Right b2) = a1 == b2

aretheyeq :: (Eq a, Eq b) => Either a b -> Either a b -> Bool
aretheyeq (Left a1) (Right b2) = a1 === b2

Neither aretheyreallyeq or aretheyeq compile, but the error for aretheyreallyeq makes sense to me, and also tells me that aretheyeq should not give an error: One of the instances that GHCi suggests are possible for EqM in aretheyeq should be impossible due to the same error on aretheyreallyeq. What's going on?

The point is, GHCi insists that both of the instances of EqM are applicable in aretheyeq. But a1 is of type a and b2 is of type b, so in order for the first instance to be applicable, it would have to have the types a and b unify.

But this should not be possible, since they are declared as type variables at the function signature (that is, using the first EqM instance would give rise to the function being of type Either a a -> Either a a -> Bool, and the error in aretheyreallyeq tells me that GHCi will not allow that (which is what I expected anyway).

Am I missing something, or is this a bug in how overlapping instances with multi-parameter type classes are checked?

I am thinking maybe it has to do with the fact that a and b could be further instantiated later on to the point where they are equal, outside aretheyeq, and then the first instance would be valid? But the same is true for aretheyreallyeq. The only difference is that if they do not ever unify we have an option for aretheyeq, but we do not for aretheyreallyeq. In any case, Haskell does not have dynamic dispatch for plenty of good and obvious reasons, so what is the fear in committing to the instance that will always work regardless of whether later on a and b are unifiable? Maybe there is some way to present this that would make choosing the instance when calling the function possible in some way?

It is worth noting that if I remove the second instance, then the function obviously still does not compile, stating that no instance EqM a b can be found. So if I do not have that instance, then none works, but when that one works, suddenly the other does too and I have an overlap? Smells like bug to me miles away.

Body:
To further complete Alexey's answer, which really gave me the hint at what I should do to achieve the behaviour I wanted, I compiled the following minimum working example of a slightly different situation more alike my real use case (which has to do with ExistentialQuantification):

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
module ExistentialTest where

class Class1 a b where
    foo :: a -> b

instance {-# INCOHERENT #-} Monoid a => Class1 a (Either b a) where
    foo x = Right (x <> x)

instance {-# INCOHERENT #-} Monoid a => Class1 a (Either a b) where
    foo x = Left x

data Bar a = Dir a | forall b. Class1 b a => FromB b

getA :: Bar a -> a
getA (Dir a) = a
getA (FromB b) = foo b

createBar :: Bar (Either String t)
createBar = FromB "abc"

createBar2 :: Bar (Either t String)
createBar2 = FromB "def"

If you remove the {-# INCOHERENT #-} annotations, you get exactly the same compile errors as in my original example on both createBar and createBar2, and the point is the same: in createBar it is clear that the only suitable instance is the second one, whereas in createBar2 the only suitable one is the first one, but Haskell refuses to compile because of this apparent confusion it might create when using it, until you annotate them with INCOHERENT.

And then, the code works exactly as you'd expect it to: getA createBar returns Left "abc" whereas getA createBar2 returns Right "defdef", which is exactly the only thing that could happen in a sensible type system.

So, my conclusion is: the INCOHERENT annotation is precisely to allow what I wanted to do since the beginning without Haskell complaining about potentially confusing instances and indeed taking the only one that makes sense. A doubt remains as to whether INCOHERENT may make it so that instances that indeed remain overlapping even after taking into account everything compile, using an arbitrary one (which is obviously bad and dangerous). So, a corollary to my conclusion is: only use INCOHERENT when you absolutely need to and are absolutely convinced that there is indeed only one valid instance.

I still think it is a bit absurd that Haskell has no more natural and safe way to tell the compiler to stop worrying about me being potentially being confused and doing what is obviously the only type checking answer to the problem...


问:
How to Create Chart.JS Bar Graph with Min, Max & Average
I have an app that is generating some bart charts from a service. My client added an additional chart to display a range (min, max and average). I was wondering if their is a way to accomplish this using chart.js. I looked through their docs and wasn't able to find any examples or documentation on how to accomplish this. Anyone else run into this or have a different library they prefer?

答:
I completely failed to get this working for bar charts (works for line, scatter, radar).   Then I found new chartjs 2.9 feature here Min Max bar values

Using this on bar and horizontalBar successfully.


问:
Can I put a latex table into an r data frame?
Someone else built a table using latex formatting into the r markdown file I am using. I want to be able to put the data contained in the table directly into an r data frame that I can then manipulate using r code. The table was not uploaded in a .tex file--it just looks like this in code:

```<code>\begin{table}[ht]
\begin{center}
\begin{tabular}{l|cccc|c}
\hline
  & \multicolumn{4}{c|}{\textbf{Number of Siblings}} & \\
  \textbf{Time Zone} & \textbf{1} & \textbf{2} & \textbf{3} & \textbf{4+} & \textbf{Total}\\
\hline
  \textbf{Eastern} & 3 & 6 & 1 & 14 & 24\\
  \textbf{Central} & 4 & 12 & 5 & 20 & 41\\
  \textbf{Mountain} & 21 & 6 & 3 & 7 & 37 \\
  \textbf{Pacific} & 6 & 2 & 8 & 9 & 25\\
\hline
  \textbf{Total} & 34 & 26 & 16 & 50 & 126\\
\hline
\end{tabular}
\end{center}
 \end{table}
</code>```

I want to put this into an r data frame to graph it, for example. Any help in doing this would be appreciated!

Thanks so much!

答:
Assuming that myfile.tex has the lines shown in the question and no other lines that begin with \textbf (possibly preceded by space), first read it into L, extract the lines that begin with \textbf{ (possibly preceded by space) giving L2 and then remove the \textbf{...} leaving only the enclosed part to give L3.  Now read that in using read.table giving DF.

```<code>L <- readLines("myfile.tex")
L2 <- grep("^ *.textbf", L, value = TRUE)
L3 <- gsub(".textbf.(.*?)\\}", "\\1", L2)
DF <- read.table(text = L3, sep = "&", header = TRUE,
  strip.white = TRUE, check.names = FALSE, comment.char = "\\")
</code>```

giving:

```<code>> DF
  Time Zone  1  2  3 4+ Total
1   Eastern  3  6  1 14    24
2   Central  4 12  5 20    41
3  Mountain 21  6  3  7    37
4   Pacific  6  2  8  9    25
5     Total 34 26 16 50   126
</code>```

Body:
Someone else built a table using latex formatting into the r markdown file I am using. I want to be able to put the data contained in the table directly into an r data frame that I can then manipulate using r code. The table was not uploaded in a .tex file--it just looks like this in code:

\begin{table}[ht]
\begin{center}
\begin{tabular}{l|cccc|c}
\hline
  & \multicolumn{4}{c|}{\textbf{Number of Siblings}} & \\
  \textbf{Time Zone} & \textbf{1} & \textbf{2} & \textbf{3} & \textbf{4+} & \textbf{Total}\\
\hline
  \textbf{Eastern} & 3 & 6 & 1 & 14 & 24\\
  \textbf{Central} & 4 & 12 & 5 & 20 & 41\\
  \textbf{Mountain} & 21 & 6 & 3 & 7 & 37 \\
  \textbf{Pacific} & 6 & 2 & 8 & 9 & 25\\
\hline
  \textbf{Total} & 34 & 26 & 16 & 50 & 126\\
\hline
\end{tabular}
\end{center}
 \end{table}

I want to put this into an r data frame to graph it, for example. Any help in doing this would be appreciated!

Thanks so much!

Body:
Assuming that myfile.tex has the lines shown in the question and no other lines that begin with \textbf (possibly preceded by space), first read it into L, extract the lines that begin with \textbf{ (possibly preceded by space) giving L2 and then remove the \textbf{...} leaving only the enclosed part to give L3.  Now read that in using read.table giving DF.

L <- readLines("myfile.tex")
L2 <- grep("^ *.textbf", L, value = TRUE)
L3 <- gsub(".textbf.(.*?)\\}", "\\1", L2)
DF <- read.table(text = L3, sep = "&", header = TRUE,
  strip.white = TRUE, check.names = FALSE, comment.char = "\\")

giving:

> DF
  Time Zone  1  2  3 4+ Total
1   Eastern  3  6  1 14    24
2   Central  4 12  5 20    41
3  Mountain 21  6  3  7    37
4   Pacific  6  2  8  9    25
5     Total 34 26 16 50   126


问:
RecyclerView remains empty with Paging Library and PositionalDataSource
I am trying to configure the Android Paging library in my project to load a paginated list of messages into a RecyclerView. Since my API uses offset and max, I'm using a PositionalDataSource.

Here is my DataSource implementation, where DataStore is using RetroFit to load the messages, and I can see in the console that messages are being loaded properly, and converted to instances of MessageListItem:

```<code>class MessageDataSource: PositionalDataSource<MessageListItem>() {
    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MessageListItem>) {
        DataStore.shared.loadMessages(params.startPosition, params.loadSize) { result, error ->
            if(result != null) {
                callback.onResult(result.items)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }

    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<MessageListItem>
    ) {
        DataStore.shared.loadMessages(params.requestedStartPosition, params.requestedLoadSize) { response, error ->
            if(response != null) {
                callback.onResult(response.items, response.offset, response.total)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }
}

class MessageDataSourceException(rootCause: Throwable? = null): Exception(rootCause)
</code>```

Here is my DataSourceFactory implementation:

```<code>class MessageDataSourceFactory: DataSource.Factory<Int, MessageListItem>() {
    val messageLiveDataSource = MutableLiveData<MessageDataSource>()
    private lateinit var messageDataSource: MessageDataSource

    override fun create(): DataSource<Int, MessageListItem> {
        messageDataSource = MessageDataSource()
        messageLiveDataSource.postValue(messageDataSource)
        return messageDataSource
    }
}
</code>```

Here is my MessageListAdapter implementation:

```<code>object MessageListItemDiff: DiffUtil.ItemCallback<MessageListItem>() {
    override fun areItemsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem == newItem
    }
}

class MessageListAdapter(private val clickListener: View.OnClickListener):
    PagedListAdapter<MessageListItem, MessageListAdapter.MessageHolder>(MessageListItemDiff) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageHolder {
        val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false)
        return MessageHolder(inflatedView, clickListener)
    }

    override fun onBindViewHolder(holder: MessageHolder, position: Int) {
        holder.bind(getItem(position)!!)
    }

    class MessageHolder(itemView: View, private val clickListener: View.OnClickListener) : RecyclerView.ViewHolder(itemView) {
        val unreadIndicator = itemView.findViewById<ImageView>(R.id.unreadIndicator)
        val title = itemView.findViewById<TextView>(R.id.title)
        val dateSent = itemView.findViewById<TextView>(R.id.dateSent)
        val cardView = itemView.findViewById<CardView>(R.id.card_view)

        fun bind(message: MessageListItem) {
            cardView.tag = message
            cardView.setOnClickListener(clickListener)
            title.text = message.title
            dateSent.text = TimeAgo.using(message.dateSent.time)
            if(message.isRead) {
                unreadIndicator.setImageResource(0)
            } else {
                unreadIndicator.setImageResource(R.drawable.ic_unread)
            }
        }
    }
}
</code>```

And finally my ViewModel:

```<code>class MessageListViewModel: ViewModel() {
    val messagePagedList: LiveData<PagedList<MessageListItem>>
    val liveDataSource: LiveData<MessageDataSource>

    init {
        val messageDataSourceFactory = MessageDataSourceFactory()
        liveDataSource = messageDataSourceFactory.messageLiveDataSource

        val pagedListConfig = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(30)
            .setPrefetchDistance(90)
            .build()
        messagePagedList = LivePagedListBuilder(messageDataSourceFactory, pagedListConfig).build()
    }
}
</code>```

And here is the onViewCreated implementation in the fragment that is supposed to display the recycler view called messageList:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        messageList.layoutManager = LinearLayoutManager(context!!)
        messageList.setHasFixedSize(true)

        messageListViewModel = ViewModelProvider(this).get(MessageListViewModel::class.java)
        messageListAdapter = MessageListAdapter(this)

        messageListViewModel.messagePagedList.observe(this, Observer { messages ->
            messageListAdapter.submitList(messages)
        })

        messageList.adapter = messageListAdapter
    }
</code>```

The problem is that I can see that data is being loaded from the server, but it never reaches the recycler view. If I add a breakpoint on the observer line (messageListAdapter.submitList(messages)), I get a call once with an empty message list, and that's it.

I have to admit I'm really confused with all these classes and what they are supposed to do, this is my first Paging implementation in Android, and I had to adapt code I found here and there because I didn't want to use a Room database, RxJava or a PageKeyedDataSource, which most samples out there do.

Any idea what might be going on?

答:
Change this:

```<code>messageListViewModel.messagePagedList.observe(this, Observer { messages ->
    messageListAdapter.submitList(messages)
})
</code>```

with this:

```<code>messageListViewModel.messagePagedList.observe(viewLifeCycleOwner, PagedList(messageListAdapter::submitList))
</code>```

Source: https://developer.android.com/topic/libraries/architecture/paging#ex-observe-livedata

Body:
I am trying to configure the Android Paging library in my project to load a paginated list of messages into a RecyclerView. Since my API uses offset and max, I'm using a PositionalDataSource.

Here is my DataSource implementation, where DataStore is using RetroFit to load the messages, and I can see in the console that messages are being loaded properly, and converted to instances of MessageListItem:

class MessageDataSource: PositionalDataSource<MessageListItem>() {
    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MessageListItem>) {
        DataStore.shared.loadMessages(params.startPosition, params.loadSize) { result, error ->
            if(result != null) {
                callback.onResult(result.items)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }

    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<MessageListItem>
    ) {
        DataStore.shared.loadMessages(params.requestedStartPosition, params.requestedLoadSize) { response, error ->
            if(response != null) {
                callback.onResult(response.items, response.offset, response.total)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }
}

class MessageDataSourceException(rootCause: Throwable? = null): Exception(rootCause)

Here is my DataSourceFactory implementation:

class MessageDataSourceFactory: DataSource.Factory<Int, MessageListItem>() {
    val messageLiveDataSource = MutableLiveData<MessageDataSource>()
    private lateinit var messageDataSource: MessageDataSource

    override fun create(): DataSource<Int, MessageListItem> {
        messageDataSource = MessageDataSource()
        messageLiveDataSource.postValue(messageDataSource)
        return messageDataSource
    }
}

Here is my MessageListAdapter implementation:

object MessageListItemDiff: DiffUtil.ItemCallback<MessageListItem>() {
    override fun areItemsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem == newItem
    }
}

class MessageListAdapter(private val clickListener: View.OnClickListener):
    PagedListAdapter<MessageListItem, MessageListAdapter.MessageHolder>(MessageListItemDiff) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageHolder {
        val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false)
        return MessageHolder(inflatedView, clickListener)
    }

    override fun onBindViewHolder(holder: MessageHolder, position: Int) {
        holder.bind(getItem(position)!!)
    }

    class MessageHolder(itemView: View, private val clickListener: View.OnClickListener) : RecyclerView.ViewHolder(itemView) {
        val unreadIndicator = itemView.findViewById<ImageView>(R.id.unreadIndicator)
        val title = itemView.findViewById<TextView>(R.id.title)
        val dateSent = itemView.findViewById<TextView>(R.id.dateSent)
        val cardView = itemView.findViewById<CardView>(R.id.card_view)

        fun bind(message: MessageListItem) {
            cardView.tag = message
            cardView.setOnClickListener(clickListener)
            title.text = message.title
            dateSent.text = TimeAgo.using(message.dateSent.time)
            if(message.isRead) {
                unreadIndicator.setImageResource(0)
            } else {
                unreadIndicator.setImageResource(R.drawable.ic_unread)
            }
        }
    }
}

And finally my ViewModel:

class MessageListViewModel: ViewModel() {
    val messagePagedList: LiveData<PagedList<MessageListItem>>
    val liveDataSource: LiveData<MessageDataSource>

    init {
        val messageDataSourceFactory = MessageDataSourceFactory()
        liveDataSource = messageDataSourceFactory.messageLiveDataSource

        val pagedListConfig = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(30)
            .setPrefetchDistance(90)
            .build()
        messagePagedList = LivePagedListBuilder(messageDataSourceFactory, pagedListConfig).build()
    }
}

And here is the onViewCreated implementation in the fragment that is supposed to display the recycler view called messageList:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        messageList.layoutManager = LinearLayoutManager(context!!)
        messageList.setHasFixedSize(true)

        messageListViewModel = ViewModelProvider(this).get(MessageListViewModel::class.java)
        messageListAdapter = MessageListAdapter(this)

        messageListViewModel.messagePagedList.observe(this, Observer { messages ->
            messageListAdapter.submitList(messages)
        })

        messageList.adapter = messageListAdapter
    }

The problem is that I can see that data is being loaded from the server, but it never reaches the recycler view. If I add a breakpoint on the observer line (messageListAdapter.submitList(messages)), I get a call once with an empty message list, and that's it.

I have to admit I'm really confused with all these classes and what they are supposed to do, this is my first Paging implementation in Android, and I had to adapt code I found here and there because I didn't want to use a Room database, RxJava or a PageKeyedDataSource, which most samples out there do.

Any idea what might be going on?

Body:
Change this:

messageListViewModel.messagePagedList.observe(this, Observer { messages ->
    messageListAdapter.submitList(messages)
})

with this:

messageListViewModel.messagePagedList.observe(viewLifeCycleOwner, PagedList(messageListAdapter::submitList))

Source: https://developer.android.com/topic/libraries/architecture/paging#ex-observe-livedata


问:
Best practice for the directory/location of your interfaces (as in implements)
What is best practice for the directory/location of your interfaces? (as in implements)
in the folder with the class you are interfacing? an interface folder in the source root?

答:
This isn't a question with a back-and-white answer.  That said, it is my personal opinion that it makes most sense for an interface to live in the same package as the classes which implement it (or as close as possible).  That way others who use your code can infer some thing about the interface and its intended use from the package structure.

When all the interfaces are in an "interface" folder on the root 1 - that folder can get really big & ugly, 2 - the interfaces are totally disconnected from all the related files, so it's more difficult to move them around as a group,  3 - your only clue about what the interface does (without actually opening it or importing it and examining its docs and members) is the file name.


问:
iframe content from external source not loading in local HTML file on iOS
I created a local HTML file in my iOS app written in swift. The HTML file is loaded into a WKWebView as follows:

let url = Bundle(identifier: myIdentifier).url(forResource: "localHtmlFile", withExtension: "html")
let htmlFormatString = try String(contentsOf: url)
loadHTMLString(string: htmlFormatString, baseURL: nil)
```

<p>The HTML page contains an iframe which I expect to load an external page:</p>

<pre class="lang-html prettyprint-override"><code><div>Test</div>
<iframe src="https://www.somepage.com"></iframe>
</code>```

The local HTML file is loaded successfully, as I can see the Test text in the div. The iframe is also created, but empty. If I debug with Safari Developer Tools, there is just an empty html page, but nothing loaded. Also, a network request to the url is not performed at all.

But if I insert an external JavaScript file with

答:
Based on some googling, it looks like you need to use the delegate method for the webView to allow external sites.  Specifically, implement webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) with the following recommended implementation:

```<code>func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    guard let requestURL = navigationAction.request.url?.absoluteString else { return }

    if requestURL.contains("somepage.com") {
        decisionHandler(.allow)
    }
    else {
        // You don't need to cancel here, but you can implement your own logic here
        decisionHandler(.cancel)
    }
}
</code>```

Body:
I created a local HTML file in my iOS app written in swift. The HTML file is loaded into a WKWebView as follows:

let url = Bundle(identifier: myIdentifier).url(forResource: "localHtmlFile", withExtension: "html")
let htmlFormatString = try String(contentsOf: url)
loadHTMLString(string: htmlFormatString, baseURL: nil)

The HTML page contains an iframe which I expect to load an external page:

Test

The local HTML file is loaded successfully, as I can see the Test text in the div. The iframe is also created, but empty. If I debug with Safari Developer Tools, there is just an empty html page, but nothing loaded. Also, a network request to the url is not performed at all.

But if I insert an external JavaScript file with

Body:
Based on some googling, it looks like you need to use the delegate method for the webView to allow external sites.  Specifically, implement webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) with the following recommended implementation:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    guard let requestURL = navigationAction.request.url?.absoluteString else { return }

    if requestURL.contains("somepage.com") {
        decisionHandler(.allow)
    }
    else {
        // You don't need to cancel here, but you can implement your own logic here
        decisionHandler(.cancel)
    }
}


问:
Prompt for User to Save a Form
I have one last question for the moment for my class database.  For certain forms where a user can view data, I want them to be able to close the form and not be prompted if they did not make any changes.  HOWEVER, if they chose to change some data in the form, say to edit a record, I then want them to get a pop-up box prompting the user if they want to save the change.  If they select yes, then the old record is overwritten and the change is saved to the record, but if they select no, then the record isn't changed at all and the form closes.

How can I do this?  I'm using Access 2016, and what I've tried so far results in errors.  Here are 2 methods I've tried in the forms BeforeUpdate event in VBA.

Method 1:

Private Sub Form_BeforeUpdate(Cancel As Integer)

   Dim strMsg As String
   Dim iResponse As Integer

   ' Specify the message to display.
   strMsg = "Do you wish to save the changes?" & Chr(10)
   strMsg = strMsg & "Click Yes to Save or No to Discard changes."

   ' Display the message box.
   iResponse = MsgBox(strMsg, vbQuestion + vbYesNo, "Save Record?")

   ' Check the user's response.
   If iResponse = vbNo Then

      ' Undo the change.
      DoCmd.RunCommand acCmdUndo

      ' Cancel the update.
      Cancel = True
   End If
End Sub
```

<hr>

<blockquote>
  <p>Error - "The expression Before Update you entered as the event property setting produced the following error: A problem occured while Microsoft Access was communicated with the OLE server or ActiveX Control."</p>
</blockquote>

<p><strong>Method 2:</strong></p>

<pre class="lang-vb prettyprint-override"><code>Private Sub Form_BeforeUpdate(Cancel As Integer)

'Provide the user with the option to save/undo
'changes made to the record in the form

    If MsgBox("Changes have been made to this record." _
        & vbCrLf & vbCrLf & "Do you want to save these changes?" _
        , vbYesNo, "Changes Made...") = vbYes Then
            DoCmd.Save
        Else
            DoCmd.RunCommand acCmdUndo
    End If
End Sub
</code>```

Error - Same as above.

Any help is greatly appreciated!

Thanks!

答:
```<code> On Error GoTo Err_BeforeUpdate

   ' The Dirty property is True if the record has been changed.
   If Me.Dirty Then
      ' Prompt to confirm the save operation.
      If MsgBox("Do you want to save changes?", vbYesNo + vbQuestion, _
              "Save Record") = vbNo Then
         Me.Undo
      End If
   End If

Exit_BeforeUpdate:
   Exit Sub

Err_BeforeUpdate:
   MsgBox Err.Number & " " & Err.Description
   Resume Exit_BeforeUpdate
</code>```

Title: Prompt for User to Save a Form

Body:
I have one last question for the moment for my class database.  For certain forms where a user can view data, I want them to be able to close the form and not be prompted if they did not make any changes.  HOWEVER, if they chose to change some data in the form, say to edit a record, I then want them to get a pop-up box prompting the user if they want to save the change.  If they select yes, then the old record is overwritten and the change is saved to the record, but if they select no, then the record isn't changed at all and the form closes.

How can I do this?  I'm using Access 2016, and what I've tried so far results in errors.  Here are 2 methods I've tried in the forms BeforeUpdate event in VBA.

Method 1:

Private Sub Form_BeforeUpdate(Cancel As Integer)

   Dim strMsg As String
   Dim iResponse As Integer

   ' Specify the message to display.
   strMsg = "Do you wish to save the changes?" & Chr(10)
   strMsg = strMsg & "Click Yes to Save or No to Discard changes."

   ' Display the message box.
   iResponse = MsgBox(strMsg, vbQuestion + vbYesNo, "Save Record?")

   ' Check the user's response.
   If iResponse = vbNo Then

      ' Undo the change.
      DoCmd.RunCommand acCmdUndo

      ' Cancel the update.
      Cancel = True
   End If
End Sub

Error - "The expression Before Update you entered as the event property setting produced the following error: A problem occured while Microsoft Access was communicated with the OLE server or ActiveX Control."

Method 2:

Private Sub Form_BeforeUpdate(Cancel As Integer)

'Provide the user with the option to save/undo
'changes made to the record in the form

    If MsgBox("Changes have been made to this record." _
        & vbCrLf & vbCrLf & "Do you want to save these changes?" _
        , vbYesNo, "Changes Made...") = vbYes Then
            DoCmd.Save
        Else
            DoCmd.RunCommand acCmdUndo
    End If
End Sub

Error - Same as above.

Any help is greatly appreciated!

Thanks!


问:
Upload multi part file to S3
I am using spring boot and I have a multipart file from request that I need to upload to S3,but S3 only supports file(not multipart file) to upload to S3.
How to upload multipart file to s3</p>

答:
You can convert the multipart file to file like this:

```<code>private File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = new File(file.getOriginalFilename());
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
}
</code>```

But this will create a file in your system s you need to delete it after you upload it using :

```<code>if(file.exists()){
  FileUtils.deleteQuietly(file);
}
</code>```

But if you don't want to involve this path then you can directly upload the stream to s3.

```<code>PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)
</code>```

where:

```<code>input =file.getinputstream();
ObjectMetadata metadata=new ObjectMetadata();
metadata.setContentLength(file.size());
</code>```

Title: Upload multi part file to S3

Body:
You can convert the multipart file to file like this:

private File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = new File(file.getOriginalFilename());
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
}

But this will create a file in your system s you need to delete it after you upload it using :

if(file.exists()){
  FileUtils.deleteQuietly(file);
}

But if you don't want to involve this path then you can directly upload the stream to s3.

PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)

where:

input =file.getinputstream();
ObjectMetadata metadata=new ObjectMetadata();
metadata.setContentLength(file.size());


问:
By adding two hexadecimal numbers the flags Z,N,V and C need to be found. I have found Z,N, C flags correct but V should be 0 instead of 1. Why?
FA
+AB
=A5 (Carry of 1, 1A5) C=1

A5=A*16+5*16^0=165 (is not between -127-128 so I think it is overflow and V=1 but the correct answer is V=0)

Other answers are correct:
A5=10100101, which shows N flag is 1.
Also, Z flag is 0 because A5 is different from number 0.

答:
FA + AB

```<code>        0
 11111010
+10101011
==========

111110100
 11111010
+10101011
==========
 10100101
</code>```

The msbits of the operands are the same and the result is the same as those operands so it is not a signed overflow.  The other equivalent test is the carry in and carry out of the msbit are the same (both 1s) so no signed overflow.

```<code>0xFA + 0xAB = 0xA5
-6 + -85 = -91
</code>```

that is not a signed overflow.

N is set because the msbit of the answer is set, C is set because of the carry out (unsigned overflow which is correct 250 + 171 = 421 ).  And the answer is not zero so Z = 0.

Edit

The V bit is the SIGNED overflow bit, it only has meaning when the programmer considers these bits to be signed.  (for add and subtract the logic doesn't care/know about signed vs unsigned the logic is the same, that is the beauty of twos complement).

```<code>01111111  127
....
00000100  4
00000011  3
00000010  2
00000001  1
00000000  0
11111111 -1
11111110 -2
11111101 -3
....
10000001 -127
10000000 -128
</code>```

When you the programmer consider the bits to be signed, and are using twos complement (or even sign/magnitude), then when you see the msbit set that means the number is negative.  So we assume here in this question you are talking about 8 bit numbers so 0xFA when considered a signed number is negative, how I figure out what that is in decimal is invert and add one then convert to decimal.

So 0xFA to 0x05 then add one 0x06  convert to decimal and add a negative sign so -6  0xAB is then 0x54+1 (with experience you can simply look at the hex number and invert it and write the inverted number) or 0x55 then I use my calculator -85.  -6 + -85 in decimal is -91, which can be represented in 8 bits because 8 bits, signed, can represent between +127 and -128, -91 falls in that range, so there is no SIGNED overflow.

We need to take the two's complement because we grew up thinking decimal and want to see the number as decimal so you use the above process, another way is type say FFFFA into my calculator then negate in hex mode and get some ffs some 00s then 6 so 0x06, a quicker way, on my calculator, then re-type just the 06 and convert to decimal.  FFFFAB (don't really need to sign extend it at all, just helps me when I do it) gives 55 then convert to decimal and negate.

So the WHY we have to do it is because if we want to understand it in our decimal minds and are doing it manually that is what we do, otherwise look it up in a table, use a program, etc. to "see" the negative number, same goes for positive if we want to "see" it in decimal then if the msbit is 0 we convert it as is, if 1 then invert add one then convert that and put a negative sign on it.  There is no reason for the processor to do this it wants the bits as is, it is only when we want to SEE what the processor is doing, we like to think in decimal.

Body:
FA + AB

        0
 11111010
+10101011
==========

111110100
 11111010
+10101011
==========
 10100101

The msbits of the operands are the same and the result is the same as those operands so it is not a signed overflow.  The other equivalent test is the carry in and carry out of the msbit are the same (both 1s) so no signed overflow.

0xFA + 0xAB = 0xA5
-6 + -85 = -91

that is not a signed overflow.

N is set because the msbit of the answer is set, C is set because of the carry out (unsigned overflow which is correct 250 + 171 = 421 ).  And the answer is not zero so Z = 0.

Edit

The V bit is the SIGNED overflow bit, it only has meaning when the programmer considers these bits to be signed.  (for add and subtract the logic doesn't care/know about signed vs unsigned the logic is the same, that is the beauty of twos complement).

01111111  127
....
00000100  4
00000011  3
00000010  2
00000001  1
00000000  0
11111111 -1
11111110 -2
11111101 -3
....
10000001 -127
10000000 -128

When you the programmer consider the bits to be signed, and are using twos complement (or even sign/magnitude), then when you see the msbit set that means the number is negative.  So we assume here in this question you are talking about 8 bit numbers so 0xFA when considered a signed number is negative, how I figure out what that is in decimal is invert and add one then convert to decimal.

So 0xFA to 0x05 then add one 0x06  convert to decimal and add a negative sign so -6  0xAB is then 0x54+1 (with experience you can simply look at the hex number and invert it and write the inverted number) or 0x55 then I use my calculator -85.  -6 + -85 in decimal is -91, which can be represented in 8 bits because 8 bits, signed, can represent between +127 and -128, -91 falls in that range, so there is no SIGNED overflow.

We need to take the two's complement because we grew up thinking decimal and want to see the number as decimal so you use the above process, another way is type say FFFFA into my calculator then negate in hex mode and get some ffs some 00s then 6 so 0x06, a quicker way, on my calculator, then re-type just the 06 and convert to decimal.  FFFFAB (don't really need to sign extend it at all, just helps me when I do it) gives 55 then convert to decimal and negate.

So the WHY we have to do it is because if we want to understand it in our decimal minds and are doing it manually that is what we do, otherwise look it up in a table, use a program, etc. to "see" the negative number, same goes for positive if we want to "see" it in decimal then if the msbit is 0 we convert it as is, if 1 then invert add one then convert that and put a negative sign on it.  There is no reason for the processor to do this it wants the bits as is, it is only when we want to SEE what the processor is doing, we like to think in decimal.


问:
DatagridView: Remove unused space?
I was wondering whether it is possible to remove the unused space ( the gray space )  of the DataGridView control in C#. I have to make the DataGridView display the white table only.

Any suggestions?

Note: This post originally contained an external image that is no longer valid

答:
I have found no simple way to remove the "unused" or gray (BackgroundColor) space. However, an effective solution for me was to hide the borders of the DataGridView and to change its background color to the background of the surrounding control. In essence, the perception is that there is no more unused space.

Here is a snippet in pseudocode:

```<code>TableGridView = DataGridView()
TableGridView.Width = 0
TableGridView.Height = 0
TableGridView.AutoSize = true
TableGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
TableGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
TableGridView.BackgroundColor = SystemColors.ControlLightLight
TableGridView.BorderStyle = BorderStyle.None
</code>```

I read somewhere that the AutoSize setting is not applicable, however, it did change things for me. This example suggests that the surrounding control has a background color of SystemColors.ControlLightLight, but this can be modified as required.

Please vote this up if it helped you.

Title: DatagridView: Remove unused space?

Body:
I have found no simple way to remove the "unused" or gray (BackgroundColor) space. However, an effective solution for me was to hide the borders of the DataGridView and to change its background color to the background of the surrounding control. In essence, the perception is that there is no more unused space.

Here is a snippet in pseudocode:

TableGridView = DataGridView()
TableGridView.Width = 0
TableGridView.Height = 0
TableGridView.AutoSize = true
TableGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
TableGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
TableGridView.BackgroundColor = SystemColors.ControlLightLight
TableGridView.BorderStyle = BorderStyle.None

I read somewhere that the AutoSize setting is not applicable, however, it did change things for me. This example suggests that the surrounding control has a background color of SystemColors.ControlLightLight, but this can be modified as required.

Please vote this up if it helped you.


答: When you write out the date you will write it out with the month, day, and year. Today is 2/15/20 (I am not sure how it work in places other than America.) This establishes a standard that the number 2 corresponds to Febuary. There is no standard setting days of the week to any number so it treats them as 7 items and starts counting at 0 as normal</p>

Title: In the python datetime why is the first month, 'January', = 1, but 'Monday', the first day of the week = 0?

Body:
I was just learning about the datetime module, and noticed that when you use .month it provides the month in a range of 1 to 12, where 1 is January. When using .weekday, however, it provides the weekday in a range of 0 to 6.

Most list indexes start at 0, so why wouldn't January, from the list of months also be 0, not 1? I looked at the python datetime docs, but didn't see an explanation. Thanks in advance.


问:
Refactoring PL/SQL: many cursors with same rowtype (in theory)
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

```<code>cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();
</code>```

Then when processing the results, I have code like this:

```<code>    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;
</code>```

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

```<code>procedure sp_process_collection(in_collection t_curs1_tab) is ...
</code>```

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

答:
If the resulting columns are the same, there's no reason to have three TYPE declarations. You just have one TYPE. Whether you need one or more variables of that TYPE depends on whether you need to hold the different data sets concurrently.</p>

```<code>cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs_tab is table of c_curs1;
...
v_curs_results t_curs_tab := t_curs_tab();
...
open c_curs1;
fetch c_curs1 bulk collect into v_curs_results;
close c_curs1;
...
open c_curs2;
fetch c_curs2 bulk collect into v_curs_results;
close c_curs2;
...
open c_curs3;
fetch c_curs3 bulk collect into v_curs_results;
close c_curs3;
</code>```

Body:
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();

Then when processing the results, I have code like this:

    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

procedure sp_process_collection(in_collection t_curs1_tab) is ...

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

Body:
If the resulting columns are the same, there's no reason to have three TYPE declarations. You just have one TYPE. Whether you need one or more variables of that TYPE depends on whether you need to hold the different data sets concurrently.

cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs_tab is table of c_curs1;
...
v_curs_results t_curs_tab := t_curs_tab();
...
open c_curs1;
fetch c_curs1 bulk collect into v_curs_results;
close c_curs1;
...
open c_curs2;
fetch c_curs2 bulk collect into v_curs_results;
close c_curs2;
...
open c_curs3;
fetch c_curs3 bulk collect into v_curs_results;
close c_curs3;


问:
How can I search and access data from a widget which is in a map?
This is my example map:

Map<String, Transaction> _userTransactions = {

   'one': Transaction(amount: - 45, date: DateTime.now(), title: 'socks', accountType: 'timr', notes: 'joa' , icon: Icon(Icons.today,), id: 'kololdcd', repeat: 'always'),
   'two': Transaction(amount: - 60, date: DateTime.now(), title: 'present', accountType: 'timr', notes: 'brother' , icon: Icon(Icons.today,), id: 'kolofkfrcd', repeat: 'never'),
  } ;
  ```

I want to create a function which calculates the daily balance. Thus I need to identify all Transaction that have a certain value for the argument date (and maybe put them into a new map) Then I need access to the values from the argument amount (from the valid Transaction that we identified before) and add up all values for the daily balance.

I am new to to Futter. I tried to convert the map into a list and used the function .Where to search the date data and access the amount data, but I was confused, because I need access to values from the Widget Transaction which is in a list, which makes the thing a bit more complicated for me.

Do you have any advice how to start or better how to write the whole method?

答:
You can take the text of your question and convert it directly into the code you need.

int getDailyBalance(DateTime targetDate) {
  // (Start with a list of all the values in the map)
  return _userTransactions.values
  // ...identify all Transaction that have a certain value for the argument date
    .where((t) => t.date == targetDate)
  // Then I need access to the values from the argument amount
    .map((t) => t.amount)
  // ...add up all values for the daily balance
    .reduce((a1, a2) => a1 + a2)
  // (Default to zero if no matching values are found [optional])
    ?? 0;;
}
```

Body:
This is my example map:

Map<String, Transaction> _userTransactions = {

   'one': Transaction(amount: - 45, date: DateTime.now(), title: 'socks', accountType: 'timr', notes: 'joa' , icon: Icon(Icons.today,), id: 'kololdcd', repeat: 'always'),
   'two': Transaction(amount: - 60, date: DateTime.now(), title: 'present', accountType: 'timr', notes: 'brother' , icon: Icon(Icons.today,), id: 'kolofkfrcd', repeat: 'never'),
  } ;

I want to create a function which calculates the daily balance. Thus I need to identify all Transaction that have a certain value for the argument date (and maybe put them into a new map) Then I need access to the values from the argument amount (from the valid Transaction that we identified before) and add up all values for the daily balance.

I am new to to Futter. I tried to convert the map into a list and used the function .Where to search the date data and access the amount data, but I was confused, because I need access to values from the Widget Transaction which is in a list, which makes the thing a bit more complicated for me.

Do you have any advice how to start or better how to write the whole method?


问:
Why are these two types different?
I split String to String[] arr and want to compare element of arr with String
but I don't know why System.out.println(arr[0] == "P"); return 'false'

Please check my code and answer to me. Thank you!

```<code>enter code here
String s = "pPooyy";
s = s.toUpperCase();
String[] arr;
arr = s.split("");

System.out.println(arr[0]);
System.out.println(arr[0] == "P");
</code>```

this is result.
P
false

System.out.println(arr[0]); -> the result of this println is P so I thought System.out.println(arr[0] == "P"); would return 'true' but it wasn't.

Why  are these two types different?

答:
Why not use charAt ?

```<code>Syso(s.charAt(0)=='P')
</code>```

Let me know if this helps

Title: Why are these two types different?

Body:
I split String to String[] arr and want to compare element of arr with String
but I don't know why System.out.println(arr[0] == "P"); return 'false'

Please check my code and answer to me. Thank you!

enter code here
String s = "pPooyy";
s = s.toUpperCase();
String[] arr;
arr = s.split("");

System.out.println(arr[0]);
System.out.println(arr[0] == "P");

this is result.
P
false

System.out.println(arr[0]); -> the result of this println is P so I thought System.out.println(arr[0] == "P"); would return 'true' but it wasn't.

Why  are these two types different?

Body:
Why not use charAt ?

Syso(s.charAt(0)=='P')

Let me know if this helps


问:
How do I show the total number of sales orders per year for each sales representative using CTE in SQL Server?
I've been trying to show the total number of sales orders per year for each sales representative using CTE but my logic is messed up. I don't even know what I'm doing?</p>

```<code>WITH TotalNumber
AS (
    -- Query Here
    SELECT SalesPersonID
        ,SalesOrderID
        ,YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
    ORDER BY SalesYear ASC
    )
SELECT DISTINCT YEAR(OrderDate)
FROM Sales.SalesOrderHeader
</code>```

答:
You can achieve it in this way</p>

```<code>SELECT SalesPersonID, YEAR(OrderDate) AS SalesYear, COUNT(SalesOrderID) AS Total_number_of _sales_orders
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
GROUP BY SalesPersonID, YEAR(OrderDate)
ORDER BY SalesYear ASC
</code>```

Body:
I've been trying to show the total number of sales orders per year for each sales representative using CTE but my logic is messed up. I don't even know what I'm doing?

WITH TotalNumber
AS (
    -- Query Here
    SELECT SalesPersonID
        ,SalesOrderID
        ,YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
    ORDER BY SalesYear ASC
    )
SELECT DISTINCT YEAR(OrderDate)
FROM Sales.SalesOrderHeader

Body:
You can achieve it in this way

SELECT SalesPersonID, YEAR(OrderDate) AS SalesYear, COUNT(SalesOrderID) AS Total_number_of _sales_orders
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
GROUP BY SalesPersonID, YEAR(OrderDate)
ORDER BY SalesYear ASC


问:
parse_exception - request body is required
I'm trying to insert a JSON data file in my elasticsearch instance.

curl  -s -H “Content-Type: application/x-ndjson” -XPOST localhost:9200/_bulk —-data-binary “@restaurants.json”; echo

However, after executing this command I get an error that says

{"error":{"root_cause":[{"type":"parse_exception","reason":"request body is required"}],"type":"parse_exception","reason":"request body is required"},"status":400}

The JSON file basically has an array of the below object.
Only thing is that I've put just one object here to save space. However, there are more than one objects present.

Structure is like given below;

```<code>[
   {
      "address": {
         "building": "351",
         "coord": [
            -73.98513559999999,
            40.7676919
         ],
         "street": "West   57 Street",
         "zipcode": "10019"
      },
      "borough": "Manhattan",
      "cuisine": "Irish",
      "name": "Dj Reynolds Pub And Restaurant",
      "grades": [
         {
            "date": {
               "$date": "2014-09-06T00:00:00.000Z"
            },
            "grade": "A",
            "score": 2
         },
         {
            "date": {
               "$date": "2013-07-22T00:00:00.000Z"
            },
            "grade": "A",
            "score": 11
         },
         {
            "date": {
               "$date": "2012-07-31T00:00:00.000Z"
            },
            "grade": "A",
            "score": 12
         },
         {
            "date": {
               "$date": "2011-12-29T00:00:00.000Z"
            },
            "grade": "A",
            "score": 12
         }
      ],
      "id": "30191841"
   }
]
</code>```

答:
I solved it by wrapping the url with quotation mark.</p>

```<code>curl  -s -H “Content-Type: application/x-ndjson” -XPOST "localhost:9200/_bulk —-data-binary “@restaurants.json”;
</code>```

Body:
I'm trying to insert a JSON data file in my elasticsearch instance.

curl  -s -H “Content-Type: application/x-ndjson” -XPOST localhost:9200/_bulk —-data-binary “@restaurants.json”; echo

However, after executing this command I get an error that says

{"error":{"root_cause":[{"type":"parse_exception","reason":"request body is required"}],"type":"parse_exception","reason":"request body is required"},"status":400}

The JSON file basically has an array of the below object.
Only thing is that I've put just one object here to save space. However, there are more than one objects present.

Structure is like given below;

[
   {
      "address": {
         "building": "351",
         "coord": [
            -73.98513559999999,
            40.7676919
         ],
         "street": "West   57 Street",
         "zipcode": "10019"
      },
      "borough": "Manhattan",
      "cuisine": "Irish",
      "name": "Dj Reynolds Pub And Restaurant",
      "grades": [
         {
            "date": {
               "$date": "2014-09-06T00:00:00.000Z"
            },
            "grade": "A",
            "score": 2
         },
         {
            "date": {
               "$date": "2013-07-22T00:00:00.000Z"
            },
            "grade": "A",
            "score": 11
         },
         {
            "date": {
               "$date": "2012-07-31T00:00:00.000Z"
            },
            "grade": "A",
            "score": 12
         },
         {
            "date": {
               "$date": "2011-12-29T00:00:00.000Z"
            },
            "grade": "A",
            "score": 12
         }
      ],
      "id": "30191841"
   }
]

Body:
I solved it by wrapping the url with quotation mark.

curl  -s -H “Content-Type: application/x-ndjson” -XPOST "localhost:9200/_bulk —-data-binary “@restaurants.json”;