问:
Need to convert a date 09/01/2009 to a CHAR TYPE FORMAT
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

```<code>SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;
</code>```

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

答:
```<code>SQL> -- Examples of the conversion functions.
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  d1    DATE;
  d2    DATE;
  d3    DATE;
  d4    DATE;
BEGIN
  d1 := TO_DATE('1/1/02','mm/dd/yy');
  d2 := TO_DATE('1-1-1998','mm-dd-yyyy');
  d3 := TO_DATE('Jan 1, 2000','mon dd,yyyy');
  d4 := TO_DATE('1/1/02','mm/dd/rr');

  DBMS_OUTPUT.PUT_LINE('d1 = ' || TO_CHAR(d1,'dd-Mon-yyyy'));
  DBMS_OUTPUT.PUT_LINE('d2 = ' || TO_CHAR(d2,'mm/dd/yyyy'));
  DBMS_OUTPUT.PUT_LINE('d3 = ' || TO_CHAR(d3,'Day, Month dd, yyyy'));
  DBMS_OUTPUT.PUT_LINE('d4 = ' || TO_CHAR(d4,'Dy, Mon dd, yyyy'));

END;
</code>```

Take the hint form this

Body:
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

Body:
SQL> -- Examples of the conversion functions.
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  d1    DATE;
  d2    DATE;
  d3    DATE;
  d4    DATE;
BEGIN
  d1 := TO_DATE('1/1/02','mm/dd/yy');
  d2 := TO_DATE('1-1-1998','mm-dd-yyyy');
  d3 := TO_DATE('Jan 1, 2000','mon dd,yyyy');
  d4 := TO_DATE('1/1/02','mm/dd/rr');

  DBMS_OUTPUT.PUT_LINE('d1 = ' || TO_CHAR(d1,'dd-Mon-yyyy'));
  DBMS_OUTPUT.PUT_LINE('d2 = ' || TO_CHAR(d2,'mm/dd/yyyy'));
  DBMS_OUTPUT.PUT_LINE('d3 = ' || TO_CHAR(d3,'Day, Month dd, yyyy'));
  DBMS_OUTPUT.PUT_LINE('d4 = ' || TO_CHAR(d4,'Dy, Mon dd, yyyy'));

END;

Take the hint form this


来源: stackexchange

问:
After upgrading flutter version from v1.12.13+hotfix.8 to 1.17.0 getting such error
Compiler message:
../../../Public/FlutterSDK/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_cupertino_date_picker-1.0.12/lib/src/date_picker_theme.dart:39:9: Error: The superclass, 'Diagnosticable', has no unnamed constructor that takes no arguments.
  const DateTimePickerTheme({
        ^^^^^^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.</p>

答:
If you are using flutter_cupertino_date_picker, you may be will need to update it, This is working with me:

```<code>flutter_cupertino_date_picker: ^1.0.26
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you are using flutter_cupertino_date_picker, you may be will need to update it, This is working with me:

flutter_cupertino_date_picker: ^1.0.26


问:
how to handle API unified return format in flutter
I have some probem when decode api data to dart model, below is the api response

{
        "code": 200,
        "message": "操作成功",
        "data": [
            { "id": 4, "locationId": 1, "coverImg": "cfe4bf63-2752-497c-bb02-60c57ef3f22f.png", "redirectType": 1, "redirectValue": "12", "sort": 12, "isDeleted": 0, "createTime": null, "updateTime": "2020-05-12 11:14:25" },
            { "id": 5, "locationId": 1, "coverImg": "d3bf3347-36ce-40ab-bc5b-78a779a3d58e.png", "redirectType": 1, "redirectValue": "10", "sort": 12, "isDeleted": 0, "createTime": null, "updateTime": "2020-05-12 11:14:48" },
            { "id": 16, "locationId": 1, "coverImg": "0a1aeb3f-8850-42e5-b7df-307eca058fed.png", "redirectType": 1, "redirectValue": "15", "sort": 5, "isDeleted": 0, "createTime": "2020-05-13 15:00:39", "updateTime": "2020-05-13 15:00:39" }
        ]
    }

i want conver this json string to Model below

```<code>class CommonResult<T> {
  final int code;
  final T data;
  final String message;

  CommonResult(this.code, this.data, this.message);

  CommonResult.fromJson(Map<String, dynamic> json)
  : code =json['code'],
    data = json['data'],
    message =json['message'];
}

class Banner {
  final String coverImg;
  final int id;
  final int isDelete;
  final int locationId;
  final int sort;
  final String redirectValue;
  final int redirectType;

  Banner(this.coverImg, this.id, this.isDelete, this.locationId,
      this.sort, this.redirectValue, this.redirectType);

  Banner.fromJson(Map<String, dynamic> json)
  : id =json['id'],
    coverImg = json['coverImg'],
    isDelete = json['isDelete'],
    locationId = json['locationId'],
    sort = json['sort'],
    redirectValue = json['redirectValue'],
    redirectType = json['redirectType'];
}
</code>```

convert code

```<code>    Future<List<Banner>> getHttp() async {
        Response response;
        Dio dio = new Dio();
        response = await dio.get("url");
        print(response);
        var bannerResult = CommonResult<List<Banner>>.fromJson(response.data);
        return bannerResult.data;
  }

      @override
      void initState() {
        getHttp().then((value) {
          print(value);
        });
      }
</code>```

then result in console throw Exception  Unhandled Exception: type 'List' is not a subtype of type 'List'

```<code>flutter: {"code":200,"message":"操作成功","data":[{"id":4,"locationId":1,"coverImg":"cfe4bf63-2752-497c-bb02-60c57ef3f22f.png","redirectType":1,"redirectValue":"12","sort":12,"isDeleted":0,"createTime":null,"updateTime":"2020-05-12 11:14:25"},{"id":5,"locationId":1,"coverImg":"d3bf3347-36ce-40ab-bc5b-78a779a3d58e.png","redirectType":1,"redirectValue":"10","sort":12,"isDeleted":0,"createTime":null,"updateTime":"2020-05-12 11:14:48"},{"id":16,"locationId":1,"coverImg":"0a1aeb3f-8850-42e5-b7df-307eca058fed.png","redirectType":1,"redirectValue":"15","sort":5,"isDeleted":0,"createTime":"2020-05-13 15:00:39","updateTime":"2020-05-13 15:00:39"},{"id":18,"locationId":1,"coverImg":"bf59eda5-2baa-4f70-9581-642eaf533e7b.png","redirectType":2,"redirectValue":"https://c1111.com/","sort":0,"isDeleted":0,"createTime":"2020-05-13 15:03:3<…>
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Banner>'
#0      new CommonResult.fromJson (package:recruit_app/models/commonResult.dart:15:10)
#1      _HomePageState.getHttp (package:recruit_app/pages/HomePage.dart:81:24)
<asynchronous suspension>
#2      _HomePageState.initState (package:recruit_app/pages/HomePage.dart:88:5)
#3      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
#4      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
</code>```

答:
I suggest you sperate the Object data and the List data

```<code>class BaseEntity<T> {
  int code;
  String message;
  T data;

  BaseEntity({this.code, this.message, this.data});

  factory BaseEntity.fromJson(json) {
    var data;
    if (json[RESPONSE_DATA] != null)
      data = JsonConvert.fromJsonAsT<T>(json[RESPONSE_DATA]);

    return BaseEntity(
        code: json[RESPONSE_CODE],
        message: json[RESPONSE_MESSAGE],
        data: data);
  }
}

class BaseListEntity<T> {
  int code;
  String message;
  List<T> data;

  BaseListEntity({this.code, this.message, this.data});

  factory BaseListEntity.fromJson(json) {
    List<T> mData = List();
    if (json[RESPONSE_DATA] != null) {
      (json[RESPONSE_DATA] as List).forEach((v) {
        mData.add(JsonConvert.fromJsonAsT<T>(v));
      });
    }
    return BaseListEntity(
        code: json[RESPONSE_CODE],
        message: json[RESPONSE_MESSAGE],
        data: mData);
  }
}
</code>```

Body:
I have some probem when decode api data to dart model, below is the api response

{
        "code": 200,
        "message": "操作成功",
        "data": [
            { "id": 4, "locationId": 1, "coverImg": "cfe4bf63-2752-497c-bb02-60c57ef3f22f.png", "redirectType": 1, "redirectValue": "12", "sort": 12, "isDeleted": 0, "createTime": null, "updateTime": "2020-05-12 11:14:25" },
            { "id": 5, "locationId": 1, "coverImg": "d3bf3347-36ce-40ab-bc5b-78a779a3d58e.png", "redirectType": 1, "redirectValue": "10", "sort": 12, "isDeleted": 0, "createTime": null, "updateTime": "2020-05-12 11:14:48" },
            { "id": 16, "locationId": 1, "coverImg": "0a1aeb3f-8850-42e5-b7df-307eca058fed.png", "redirectType": 1, "redirectValue": "15", "sort": 5, "isDeleted": 0, "createTime": "2020-05-13 15:00:39", "updateTime": "2020-05-13 15:00:39" }
        ]
    }

i want conver this json string to Model below

class CommonResult<T> {
  final int code;
  final T data;
  final String message;

  CommonResult(this.code, this.data, this.message);

  CommonResult.fromJson(Map<String, dynamic> json)
  : code =json['code'],
    data = json['data'],
    message =json['message'];
}

class Banner {
  final String coverImg;
  final int id;
  final int isDelete;
  final int locationId;
  final int sort;
  final String redirectValue;
  final int redirectType;

  Banner(this.coverImg, this.id, this.isDelete, this.locationId,
      this.sort, this.redirectValue, this.redirectType);

  Banner.fromJson(Map<String, dynamic> json)
  : id =json['id'],
    coverImg = json['coverImg'],
    isDelete = json['isDelete'],
    locationId = json['locationId'],
    sort = json['sort'],
    redirectValue = json['redirectValue'],
    redirectType = json['redirectType'];
}

convert code

    Future<List<Banner>> getHttp() async {
        Response response;
        Dio dio = new Dio();
        response = await dio.get("url");
        print(response);
        var bannerResult = CommonResult<List<Banner>>.fromJson(response.data);
        return bannerResult.data;
  }

      @override
      void initState() {
        getHttp().then((value) {
          print(value);
        });
      }

then result in console throw Exception  Unhandled Exception: type 'List' is not a subtype of type 'List'

flutter: {"code":200,"message":"操作成功","data":[{"id":4,"locationId":1,"coverImg":"cfe4bf63-2752-497c-bb02-60c57ef3f22f.png","redirectType":1,"redirectValue":"12","sort":12,"isDeleted":0,"createTime":null,"updateTime":"2020-05-12 11:14:25"},{"id":5,"locationId":1,"coverImg":"d3bf3347-36ce-40ab-bc5b-78a779a3d58e.png","redirectType":1,"redirectValue":"10","sort":12,"isDeleted":0,"createTime":null,"updateTime":"2020-05-12 11:14:48"},{"id":16,"locationId":1,"coverImg":"0a1aeb3f-8850-42e5-b7df-307eca058fed.png","redirectType":1,"redirectValue":"15","sort":5,"isDeleted":0,"createTime":"2020-05-13 15:00:39","updateTime":"2020-05-13 15:00:39"},{"id":18,"locationId":1,"coverImg":"bf59eda5-2baa-4f70-9581-642eaf533e7b.png","redirectType":2,"redirectValue":"https://c1111.com/","sort":0,"isDeleted":0,"createTime":"2020-05-13 15:03:3<…>
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Banner>'
#0      new CommonResult.fromJson (package:recruit_app/models/commonResult.dart:15:10)
#1      _HomePageState.getHttp (package:recruit_app/pages/HomePage.dart:81:24)
<asynchronous suspension>
#2      _HomePageState.initState (package:recruit_app/pages/HomePage.dart:88:5)
#3      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
#4      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)

Body:
I suggest you sperate the Object data and the List data

class BaseEntity<T> {
  int code;
  String message;
  T data;

  BaseEntity({this.code, this.message, this.data});

  factory BaseEntity.fromJson(json) {
    var data;
    if (json[RESPONSE_DATA] != null)
      data = JsonConvert.fromJsonAsT<T>(json[RESPONSE_DATA]);

    return BaseEntity(
        code: json[RESPONSE_CODE],
        message: json[RESPONSE_MESSAGE],
        data: data);
  }
}

class BaseListEntity<T> {
  int code;
  String message;
  List<T> data;

  BaseListEntity({this.code, this.message, this.data});

  factory BaseListEntity.fromJson(json) {
    List<T> mData = List();
    if (json[RESPONSE_DATA] != null) {
      (json[RESPONSE_DATA] as List).forEach((v) {
        mData.add(JsonConvert.fromJsonAsT<T>(v));
      });
    }
    return BaseListEntity(
        code: json[RESPONSE_CODE],
        message: json[RESPONSE_MESSAGE],
        data: mData);
  }
}


问:
Unable to use Contains in LINQ to Entity VS 2017 my query attached
my query is,

Here i am trying to get region id where the region name matches,

```<code>var Rid = db.Regions.Where(p => SqlFunctions.PatIndex("%" + Search + "%", p.RegionName) > 0).Select(p => p.RegionId).ToList();
</code>```

Change Id's comma separated in string,

```<code>string joined = string.Join(",", Rid);
</code>```

Trying to get all records related to Id's comma separated in string joined

```<code>var employ = db.Employees.Include(f => f.City).Include(f => f.Region).Where(p=>p.RegionId);
</code>```

Issue is that we dont have contain when i tried use in where clause ??

Hopes for your suggestions

答:
You should map your relationships using virtual properties:

```<code>public class Employee
{
    ...

    public int RegionId { get; set; }
    [ForeignKey("RegionId")]
    public virtual Region Region { get; set; }

    ...
}

public class Region
{
    ...

    [ForeignKey("RegionId")]
    public virtual ICollection<Employee> Employees { get; set; }

    ...
}
</code>```

Then you can use it directly in your where statement:

```<code>var employees = db.Employees
                  .Where(a => a.Region.RegionName.Contains(Search));
</code>```

or

```<code>var employees = db.Regions
                  .Where(a => a.RegionName.Contains(Search)
                  .SelectMany(a => a.Employees);
</code>```

This way you are sending less data to do your query, think of the situation where have 100 region ids selected. Also you are doing 1 query instead of 2.

Body:
my query is,

Here i am trying to get region id where the region name matches,

var Rid = db.Regions.Where(p => SqlFunctions.PatIndex("%" + Search + "%", p.RegionName) > 0).Select(p => p.RegionId).ToList();

Change Id's comma separated in string,

string joined = string.Join(",", Rid);

Trying to get all records related to Id's comma separated in string joined

var employ = db.Employees.Include(f => f.City).Include(f => f.Region).Where(p=>p.RegionId);

Issue is that we dont have contain when i tried use in where clause ??

Hopes for your suggestions

Body:
You should map your relationships using virtual properties:

public class Employee
{
    ...

    public int RegionId { get; set; }
    [ForeignKey("RegionId")]
    public virtual Region Region { get; set; }

    ...
}

public class Region
{
    ...

    [ForeignKey("RegionId")]
    public virtual ICollection<Employee> Employees { get; set; }

    ...
}

Then you can use it directly in your where statement:

var employees = db.Employees
                  .Where(a => a.Region.RegionName.Contains(Search));

or

var employees = db.Regions
                  .Where(a => a.RegionName.Contains(Search)
                  .SelectMany(a => a.Employees);

This way you are sending less data to do your query, think of the situation where have 100 region ids selected. Also you are doing 1 query instead of 2.


问:
SCNAnimationPlayer() Seems to be playing only small part of animation while using SceneKit
I made an animation in Blender and moved it to Xcode and it is converted from .dae file
to .scn by Xcode.

I can play the animation in scene graph of Xcode as it is designed in the Blender.

I am loading geometry and animation and create node for animated object.

I use SCNAnimationPlayer() to load animation. The code is below.

```<code>let scene = SCNScene(named: "scene.scn")!
let geometry = scene.rootNode.childNode(withName: "animatedGeo",
                                              recursively:true).geometry!

let animationNode = SCNNode(geometry: geometry)

let armature = scene.rootNode.childNode(withName: "Armature", recursively: true)!
let animationPlayer = armature.animationPlayer(forKey: "action_container-Armature")!
animationNode.addAnimationPlayer(animationPlayer, forKey: "action_container-Armature")

rootNode.addChildNode(animationNode)
</code>```

I did not set anything for animationPlayer programmatically because all the settings looks
Ok in scene graph window of Xcode.

However when scene loaded I see a small movement on animated object on iPhone screen.
Looks like only first (parent) bone animation is partly playing.
I could not find the why all of animation was not playing as it is played in scene graph.

答:
Yes, I found how to do it when I was trying to manipulate my object designed and animated in Blender programmatically instead of animation I made in Blender.

What you have to do is to add "Armature" node to your scene node.
This is all. You don't have to use SCNAnimationPlayer().

```<code>let scene = SCNScene(named: "scene.scn")!

let myObjectArmaturNode = scene.rootNode.childNode(withName: "Armature", recursively: true)!

rootNode.addChildNode(myObjectArmaturNode)
</code>```

This is it.
The animation runs like it is designed in Blender.
The animation consists of 4 bones by the way.

Body:
I made an animation in Blender and moved it to Xcode and it is converted from .dae file
to .scn by Xcode.

I can play the animation in scene graph of Xcode as it is designed in the Blender.

I am loading geometry and animation and create node for animated object.

I use SCNAnimationPlayer() to load animation. The code is below.

let scene = SCNScene(named: "scene.scn")!
let geometry = scene.rootNode.childNode(withName: "animatedGeo",
                                              recursively:true).geometry!

let animationNode = SCNNode(geometry: geometry)

let armature = scene.rootNode.childNode(withName: "Armature", recursively: true)!
let animationPlayer = armature.animationPlayer(forKey: "action_container-Armature")!
animationNode.addAnimationPlayer(animationPlayer, forKey: "action_container-Armature")

rootNode.addChildNode(animationNode)

I did not set anything for animationPlayer programmatically because all the settings looks
Ok in scene graph window of Xcode.

However when scene loaded I see a small movement on animated object on iPhone screen.
Looks like only first (parent) bone animation is partly playing.
I could not find the why all of animation was not playing as it is played in scene graph.

Body:
Yes, I found how to do it when I was trying to manipulate my object designed and animated in Blender programmatically instead of animation I made in Blender.

What you have to do is to add "Armature" node to your scene node.
This is all. You don't have to use SCNAnimationPlayer().

let scene = SCNScene(named: "scene.scn")!

let myObjectArmaturNode = scene.rootNode.childNode(withName: "Armature", recursively: true)!

rootNode.addChildNode(myObjectArmaturNode)

This is it.
The animation runs like it is designed in Blender.
The animation consists of 4 bones by the way.


问:
How do you make Test and Code Coverage publicly available
How do you make Test and Code Coverage from the Azure Devops publicly available, so (anonymous, without an MSDN account) users can see the results without having to have an account on your organization? I tried fiddling with the "Readers" settings within Azure DevOps but no luck. Typically, when users don't have an account the Code Coverage will load indefinitely and the Test tab is not shown.

Question 2: how can I provide a direct link (url) to my latest code-coverage for a specific build definition? Using Shield.io i was able to get a badge for the code-coverage but i also would like to provide a direct link to the report.

shields.io link to badge: https://img.shields.io/azure-devops/coverage/OffTheRecordv4/OTRv4/1

This is the project:
https://dev.azure.com/OffTheRecordv4/OTRv4/_build?definitionId=1&_a=summary

and the shield.io badge can be viewed here:
https://github.com/southernsun/otr

when logged in:

When logged out (spinning wheel never stops and nothing loads):

Thanks!

UPDATE

I created a feature request, feel free to support the request: https://developercommunity.visualstudio.com/idea/1069707/allow-code-coverage-and-test-plan-tabs-accessible.html

答:
According to your description, you are working with a public project. A public project allows non-members of a project and users who aren't signed in read-only, limited access to the project's artifacts and services. Check the following table:

To contribute to a public project, you must be added as a member of that project and assigned either Stakeholder, Basic, or Basic + Test Plans access. The access level determines the user interfaces you can access. If you want users to access Test, you would need to assign Basic + Test Plans access to them.

Regarding how to get code coverage link, you may try Code Coverage - Get Build Code Coverage API, which would give you codeCoverageFileUrl in response.


问:
Can't remove old version of ChromeDriver on MacOS
I have a very annoying problem with ChromeDriver. I need to use version 2.36, but I currently have 2.35.528157 (when doing chromedriver -v).

I have already done:

```<code>brew upgrade chromedriver
</code>```

Which ran successfully, however according to my terminal, I still have 2.35.528157

I then did a

```<code>brew cleanup chromedriver
</code>```

which got rid of versions 2.34 and 2.35 according to its logs, however when I do chromedriver -v I still get 2.35.528157.

If I do: brew list chromedriver, all I get is the following:

```<code>/usr/local/Cellar/chromedriver/2.36/bin/chromedriver
/usr/local/Cellar/chromedriver/2.36/homebrew.mxcl.chromedriver.plist
</code>```

Am I missing something?

答:
I uninstall the old version as:

```<code>brew cask uninstall chromedriver
</code>```

And then install last ( needed ) version by

```<code>brew cask install chromedriver
</code>```

So, right now my version is ok:

```<code>chromedriver --version
ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})
</code>```

And Selenium works properly

ContentLicense: CC BY-SA 3.0

Body:
I have a very annoying problem with ChromeDriver. I need to use version 2.36, but I currently have 2.35.528157 (when doing chromedriver -v).

I have already done:

brew upgrade chromedriver

Which ran successfully, however according to my terminal, I still have 2.35.528157

I then did a

brew cleanup chromedriver

which got rid of versions 2.34 and 2.35 according to its logs, however when I do chromedriver -v I still get 2.35.528157.

If I do: brew list chromedriver, all I get is the following:

/usr/local/Cellar/chromedriver/2.36/bin/chromedriver
/usr/local/Cellar/chromedriver/2.36/homebrew.mxcl.chromedriver.plist

Am I missing something?

Body:
I uninstall the old version as:

brew cask uninstall chromedriver

And then install last ( needed ) version by

brew cask install chromedriver

So, right now my version is ok:

chromedriver --version
ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})

And Selenium works properly


问:
streaming a bitmap while it is modified in C++
What I am trying to do is use some process to alter the contents of a bitmap image ( dimensions and everything else is kept constant). While I run a process to perform transformations on it, I want to concurrently stream the image to my screen as it happens. So it's basically video without a series of images, but rather the same image in different stages of a transformation.
I am trying to do this because the bitmap I want to do this with is large, so actually saving each state as its own image and then combining will not be possible due to memory constraints.

My question is regarding the "live image display" while another process modifies the image, is there any way something like this can be done with a bitmap image?

答:
You could stream the images in a video encoder directly.

For example you can feed ffmpeg with raw PGM/PPM images as input and you will get the compressed video as output without the need to ever create the actual images on disk.

Writing a PGM or PPM image means just generating a few header bytes followed by actual pixel values and thus is trivial to do with any language without the need of any image library. For example:

```<code>#include <stdio.h>
#include <math.h>
#include <algorithm>

int main(int argc, const char *argv[]) {
    int w = 1920, h = 1080;
    for (int frame=0; frame<100; frame++) {
        // output frame header
        printf("P5\n%i %i 255\n", w, h);
        for (int y=0; y<h; y++) {
            for (int x=0; x<w; x++) {
                double dx = (x - w/2),
                       dy = (y - h/2),
                       d = sqrt(dx*dx + dy*dy),
                       a = atan2(dy, dx) - frame*2*3.14159265359/100,
                       value = 127 + 127*sin(a+d/10);
                // output pixel
                putchar(std::max(0, std::min(255, int(value))));
            }
        }
    }
    return 0;
}
</code>```

generates on standard output a sequence of images that can be combined in a video directly. Running the program with

```<code>./video | ffmpeg -i - -r 60 -format pgm -y out.mp4
</code>```

will generate a video named out.mp4. The video will be at 60fps (what -r is for) created from source images in PGM format (-format pgm) from standard input (option -i -) overwriting the output file if it's already present (-y).

This code was tested on linux; for this approach to work on windows you need also to set stdout to binary more with _setmode(fileno(stdout), _O_BINARY); or something similar (I didn't test on windows).

A more sophisticated way to do basically the same would be to start a child process instead of using piping thus leaving standard output usable by the program.

Body:
You could stream the images in a video encoder directly.

For example you can feed ffmpeg with raw PGM/PPM images as input and you will get the compressed video as output without the need to ever create the actual images on disk.

Writing a PGM or PPM image means just generating a few header bytes followed by actual pixel values and thus is trivial to do with any language without the need of any image library. For example:

#include <stdio.h>
#include <math.h>
#include <algorithm>

int main(int argc, const char *argv[]) {
    int w = 1920, h = 1080;
    for (int frame=0; frame<100; frame++) {
        // output frame header
        printf("P5\n%i %i 255\n", w, h);
        for (int y=0; y<h; y++) {
            for (int x=0; x<w; x++) {
                double dx = (x - w/2),
                       dy = (y - h/2),
                       d = sqrt(dx*dx + dy*dy),
                       a = atan2(dy, dx) - frame*2*3.14159265359/100,
                       value = 127 + 127*sin(a+d/10);
                // output pixel
                putchar(std::max(0, std::min(255, int(value))));
            }
        }
    }
    return 0;
}

generates on standard output a sequence of images that can be combined in a video directly. Running the program with

./video | ffmpeg -i - -r 60 -format pgm -y out.mp4

will generate a video named out.mp4. The video will be at 60fps (what -r is for) created from source images in PGM format (-format pgm) from standard input (option -i -) overwriting the output file if it's already present (-y).

This code was tested on linux; for this approach to work on windows you need also to set stdout to binary more with _setmode(fileno(stdout), _O_BINARY); or something similar (I didn't test on windows).

A more sophisticated way to do basically the same would be to start a child process instead of using piping thus leaving standard output usable by the program.


问:
setvbuf not changing buffer size?
I have the following toy code to test out I/O buffering on fread, and I'm getting results that I didn't expect:

```<code>#include <stdio.h>
#include <stdio_ext.h>

int main()
{
    FILE *fp;
    char buff[255];
    fp = fopen("/home/install.sh", "r");
    int result = setvbuf(fp, NULL, _IOFBF, 700); // set buffering size to some arbitrary value, say 700
    printf("Result of setting buffer: %d\n", result ); // "Result of setting buffer: 0"
    printf("Buffer size: %zd\n", __fbufsize(fp) ); // "Buffer size: 4096"

    fread(buff, 255, 1, fp);
    printf("%s\n", buff ); // prints 255 bytes as I would expect

}
</code>```

From above, it seems like the setvbuf call was successful as it returned 0, however the buffer size stays at 4096. Moreover, I tried printing out BUFSIZ and it says 8192. Running strace does show the underlying read call as being 4096 bytes. Turning off buffering seems to work fine, as buffer size gets set to 1.

Moreover, I don't understand why BUFSIZ (8192) is not the same as the default value of these reads (4096).

I tried many different values for the buffer size but to no avail.

I am running ldd (Ubuntu GLIBC 2.27-3ubuntu1) 2.27

答:
I read the following here https://en.cppreference.com/w/c/io/setvbuf:

Not all size bytes will necessarily be used for buffering: the actual
  buffer size is usually rounded down to a multiple of 2, a multiple of
  page size, etc.

On many implementations, line buffering is only available for terminal
  input streams.

So maybe it doesn't work for a file handle on your system.

And if it does work, I can imagine values smaller than the allocation unit size on your file system don't make much sense (which may well be 8192).

Title: setvbuf not changing buffer size?

Body:
I have the following toy code to test out I/O buffering on fread, and I'm getting results that I didn't expect:

#include <stdio.h>
#include <stdio_ext.h>

int main()
{
    FILE *fp;
    char buff[255];
    fp = fopen("/home/install.sh", "r");
    int result = setvbuf(fp, NULL, _IOFBF, 700); // set buffering size to some arbitrary value, say 700
    printf("Result of setting buffer: %d\n", result ); // "Result of setting buffer: 0"
    printf("Buffer size: %zd\n", __fbufsize(fp) ); // "Buffer size: 4096"

    fread(buff, 255, 1, fp);
    printf("%s\n", buff ); // prints 255 bytes as I would expect

}

From above, it seems like the setvbuf call was successful as it returned 0, however the buffer size stays at 4096. Moreover, I tried printing out BUFSIZ and it says 8192. Running strace does show the underlying read call as being 4096 bytes. Turning off buffering seems to work fine, as buffer size gets set to 1.

Moreover, I don't understand why BUFSIZ (8192) is not the same as the default value of these reads (4096).

I tried many different values for the buffer size but to no avail.

I am running ldd (Ubuntu GLIBC 2.27-3ubuntu1) 2.27


问:
Trying to load chrome webdriver with extension installed,
I'm trying to load my chrome webdriver with extension installed(following the steps mentioned in 'How to load extension within chrome driver in selenium with python') but unable to find the extension installed can you please help me on this, the code I'm trying is.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension('C:/Users/john/Desktop/john/v1.10.0.0.crx')
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
</code>```

It just launches and opens the chrome webdriver with google page, I'm trying to open with extension installed is this possible using selenium, can anyone help

答:
Try calling </p>

```<code>driver = webdriver.Chrome(chrome_options=chrome_options)
</code>```

<p>instead of just </p>

```<code>driver = webdriver.Chrome()
</code>```

Body:
I'm trying to load my chrome webdriver with extension installed(following the steps mentioned in 'How to load extension within chrome driver in selenium with python') but unable to find the extension installed can you please help me on this, the code I'm trying is.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension('C:/Users/john/Desktop/john/v1.10.0.0.crx')
driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

It just launches and opens the chrome webdriver with google page, I'm trying to open with extension installed is this possible using selenium, can anyone help

Body:
Try calling

driver = webdriver.Chrome(chrome_options=chrome_options)

instead of just

driver = webdriver.Chrome()


问:
Load Url in Web View
I have a small problem that I want to load a url in web view but it doesn't displayed in webview, it displayed in default Android browser. How can we resist this to open in webview and one thing more that if I will use any other web url then it simply displayed in web view. This problem with only my particular url. What is the solution for that.

My url: http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1

my code:

```<code>@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.storesite);

    //Bundle bundle = getIntent().getExtras();
    WebView web = (WebView)findViewById(R.id.web_store);
    //MyWebViewClient web1 = new MyWebViewClient();
    //web1.shouldOverrideUrlLoading(web, "http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

}
</code>```

答:
Try this:</p>

```<code>  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the web view
    webView = (WebView) findViewById(R.id.webview);

    // prepare the web view
    registerForContextMenu(webView);
    webView.setWebViewClient(new ItemWebViewClient());
  }

  private class ItemWebViewClient extends WebViewClient {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      // show progress bar

    }

    @Override
    public void onPageFinished(WebView view, String url) {
      // hide the progress bar

    }
  }
</code>```

Title: Load Url in Web View

Body:
I have a small problem that I want to load a url in web view but it doesn't displayed in webview, it displayed in default Android browser. How can we resist this to open in webview and one thing more that if I will use any other web url then it simply displayed in web view. This problem with only my particular url. What is the solution for that.

My url: http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1

my code:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.storesite);

    //Bundle bundle = getIntent().getExtras();
    WebView web = (WebView)findViewById(R.id.web_store);
    //MyWebViewClient web1 = new MyWebViewClient();
    //web1.shouldOverrideUrlLoading(web, "http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

}

Body:
Try this:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the web view
    webView = (WebView) findViewById(R.id.webview);

    // prepare the web view
    registerForContextMenu(webView);
    webView.setWebViewClient(new ItemWebViewClient());
  }

  private class ItemWebViewClient extends WebViewClient {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      // show progress bar

    }

    @Override
    public void onPageFinished(WebView view, String url) {
      // hide the progress bar

    }
  }


问:
System.IO.StreamWriter does not contain a method named 'writeline'
I'm using PowerShell 5.1 and I've got a problem with StreamWriter.
I'm using this code :

```<code>$ExportFile = [System.IO.StreamWriter]::new("c:\temp\test.txt")
$ExportFile.WriteLine("Date,User,MyTest")
$ExportFile.Close()
</code>```

When I run the script with PowerShell ISE, it works.
But, When I run the script in PowerShell window, it does not
Here what I have :

```<code>Method invocation failed because [System.String] does not contain a method named 'WriteLine'.
At D:\Scripts\[AD MCO] Audit UsrCptr For Deletion\Audit_UsrCptr_For_Deletionv2.ps1:55 char:7
+       $ExportFile.WriteLine("Date,User, ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
PS D:\Scripts\[AD MCO] Audit UsrCptr For Deletion> host

Name             : ConsoleHost
Version          : 5.1.14393.3471
InstanceId       : 6904efae-80c0-4e51-a115-e2e580a644a7
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : fr-FR
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace
</code>```

答: I found the "error". There was a special caracter in the script that modify the execution. I wrote again the script with notepad and all is working now. Thank you for your help !</p>

Body:
I'm using PowerShell 5.1 and I've got a problem with StreamWriter.
I'm using this code :

$ExportFile = [System.IO.StreamWriter]::new("c:\temp\test.txt")
$ExportFile.WriteLine("Date,User,MyTest")
$ExportFile.Close()

When I run the script with PowerShell ISE, it works.
But, When I run the script in PowerShell window, it does not
Here what I have :

Method invocation failed because [System.String] does not contain a method named 'WriteLine'.
At D:\Scripts\[AD MCO] Audit UsrCptr For Deletion\Audit_UsrCptr_For_Deletionv2.ps1:55 char:7
+       $ExportFile.WriteLine("Date,User, ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
PS D:\Scripts\[AD MCO] Audit UsrCptr For Deletion> host

Name             : ConsoleHost
Version          : 5.1.14393.3471
InstanceId       : 6904efae-80c0-4e51-a115-e2e580a644a7
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : fr-FR
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace


问:
Dispose or kill DispatcherTimer object and Accessing DispatcherTimer object
Question 1:
Hi, I would like to know is there a way by which I can dispose or kill the object of DispatcherTimer and create a new object of same name?

Question 2:
Can I access the DispatcherTimer object in some other class if it is set to Public?

答:
Adding to a correct answer from Lubo (and bringing up this topic from comments under it): even though you cannot dispose DispatcherTimer (most probably, because it's wired up to unmanaged part of the WPF / UWP Dispatcher itself which lives as long as the app itself), you still should unsubscribe from its events.

Say, if you had some method (StartRefreshTimer) where you initialized your DispatcherTimer and started listening to its Tick event:

```<code>private DispatcherTimer _refreshTimer = new DispatcherTimer() { Interval = TimeSpan.FromMinutes(1) };

private void StartRefreshTimer()
{
    if (_refreshTimer != null)
    {
        _refreshTimer.Tick += OnTick; // subscribe to timer's ticks
        _refreshTimer.Start(); // start timer
    }
}

private void OnTick(object sender, object args)
{
    // your custom OnTick logic
}
</code>```

Then you should have a method which stops the timer and unsubscribes from its events:

```<code>private void StopRefreshTimer()
{
    if (_refreshTimer != null)
    {
        _refreshTimer.Stop(); // stop timer
        _refreshTimer.Tick -= OnTick; // unsubscribe from timer's ticks
    }
}
</code>```

You should make sure you call this "tear down" method when your class goes out of scope (for example, when your WPF / UWP control or ViewModel is unloaded). If you don't unsubscribe from timer events you could end up with memory leaks caused by references from outer scope to your timer hosting class.

Body:
Adding to a correct answer from Lubo (and bringing up this topic from comments under it): even though you cannot dispose DispatcherTimer (most probably, because it's wired up to unmanaged part of the WPF / UWP Dispatcher itself which lives as long as the app itself), you still should unsubscribe from its events.

Say, if you had some method (StartRefreshTimer) where you initialized your DispatcherTimer and started listening to its Tick event:

private DispatcherTimer _refreshTimer = new DispatcherTimer() { Interval = TimeSpan.FromMinutes(1) };

private void StartRefreshTimer()
{
    if (_refreshTimer != null)
    {
        _refreshTimer.Tick += OnTick; // subscribe to timer's ticks
        _refreshTimer.Start(); // start timer
    }
}

private void OnTick(object sender, object args)
{
    // your custom OnTick logic
}

Then you should have a method which stops the timer and unsubscribes from its events:

private void StopRefreshTimer()
{
    if (_refreshTimer != null)
    {
        _refreshTimer.Stop(); // stop timer
        _refreshTimer.Tick -= OnTick; // unsubscribe from timer's ticks
    }
}

You should make sure you call this "tear down" method when your class goes out of scope (for example, when your WPF / UWP control or ViewModel is unloaded). If you don't unsubscribe from timer events you could end up with memory leaks caused by references from outer scope to your timer hosting class.


问:
Rails: Is it bad to have an irreversible migration?
When is it acceptable to raise an ActiveRecord::IrreversibleMigration exception in the self.down method of a migration?  When should you take the effort to actually implement the reverse of the migration?</p>

答: IIRC, you'll have the IrreversibleMigration when changing a datatype in the migration.</p>

OwnerDisplayName: Readonly

ContentLicense: CC BY-SA 2.5


问:
Unable to DB2 COALESCE in Spark SQL
I have a table ENTITLE_USER from which I want to select User IDs if they are not null, else -1. For this I'm using COALESCE function of DB2. I'm reading my query inside Spark like this:

```<code>val df1 = spark.read
        .format("jdbc")
        .options(Configuration.getDbConfMap)     //Specified all necessary DB properties here
        .option("dbtable", "(SELECT COALESCE(USER_ID,0) FROM DBNFMSXR.ENTITLE_USER) AS X")
        .load()
        .withColumnRenamed("1", "USER_ID")
</code>```

When I do df1.printSchema, I am getting the following output, which is as expected:

```<code>root
 |-- USER_ID: integer (nullable = true)
</code>```

Now when I try to do df1.select("USER_ID").show() it throws up a nice stack trace of the Exception:

```<code>com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
20/06/01 13:03:33 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

20/06/01 13:03:33 ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
20/06/01 13:03:33 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/06/01 13:03:33 INFO TaskSchedulerImpl: Cancelling stage 0
20/06/01 13:03:33 INFO TaskSchedulerImpl: Killing all running tasks in stage 0: Stage cancelled
20/06/01 13:03:33 INFO DAGScheduler: ResultStage 0 (show at Test.scala:13) failed in 2.754 s due to Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
20/06/01 13:03:33 INFO DAGScheduler: Job 0 failed: show at Test.scala:13, took 2.834929 s
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:1889)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:1877)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:1876)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:58)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:51)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:926)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2082)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2101)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:365)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.collectFromPlan(Dataset.scala:3383)
    at org.apache.spark.sql.Dataset.$anonfun$head$1(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.$anonfun$withAction$2(Dataset.scala:3364)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3364)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2758)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:254)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:291)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:745)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:704)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:713)
    at me.sparker0i.before.Test$.delayedEndpoint$me$sparker0i$before$Test$1(Test.scala:13)
    at me.sparker0i.before.Test$delayedInit$body.apply(Test.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:388)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at me.sparker0i.before.Test$.main(Test.scala:3)
    at me.sparker0i.before.Test.main(Test.scala)
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

This is true in general for any DB2 queries that use COALESCE and are trying to run inside Spark JDBC.

Is there any way with which we can run queries using COALESCE inside Spark JDBC.

答:
You are renaming column 1 (which does not exist) to USER_ID.

I am not familiar with DB2 but will need to set the column name in your SQL statement:

```<code>.option("dbtable", "(SELECT COALESCE(USER_ID,0) AS USER_ID FROM DBNFMSXR.ENTITLE_USER) AS X")
</code>```

Omit the .withColumnRenamed("1", "USER_ID") and this will work.

Title: Unable to DB2 COALESCE in Spark SQL

Body:
I have a table ENTITLE_USER from which I want to select User IDs if they are not null, else -1. For this I'm using COALESCE function of DB2. I'm reading my query inside Spark like this:

val df1 = spark.read
        .format("jdbc")
        .options(Configuration.getDbConfMap)     //Specified all necessary DB properties here
        .option("dbtable", "(SELECT COALESCE(USER_ID,0) FROM DBNFMSXR.ENTITLE_USER) AS X")
        .load()
        .withColumnRenamed("1", "USER_ID")

When I do df1.printSchema, I am getting the following output, which is as expected:

root
 |-- USER_ID: integer (nullable = true)

Now when I try to do df1.select("USER_ID").show() it throws up a nice stack trace of the Exception:

com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
20/06/01 13:03:33 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

20/06/01 13:03:33 ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
20/06/01 13:03:33 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/06/01 13:03:33 INFO TaskSchedulerImpl: Cancelling stage 0
20/06/01 13:03:33 INFO TaskSchedulerImpl: Killing all running tasks in stage 0: Stage cancelled
20/06/01 13:03:33 INFO DAGScheduler: ResultStage 0 (show at Test.scala:13) failed in 2.754 s due to Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
20/06/01 13:03:33 INFO DAGScheduler: Job 0 failed: show at Test.scala:13, took 2.834929 s
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:1889)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:1877)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:1876)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:58)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:51)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:926)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2082)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2101)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:365)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.collectFromPlan(Dataset.scala:3383)
    at org.apache.spark.sql.Dataset.$anonfun$head$1(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.$anonfun$withAction$2(Dataset.scala:3364)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3364)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2758)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:254)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:291)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:745)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:704)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:713)
    at me.sparker0i.before.Test$.delayedEndpoint$me$sparker0i$before$Test$1(Test.scala:13)
    at me.sparker0i.before.Test$delayedInit$body.apply(Test.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:388)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at me.sparker0i.before.Test$.main(Test.scala:3)
    at me.sparker0i.before.Test.main(Test.scala)
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=1, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.am.k4.a(k4.java:8242)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2210)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:201)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k4.bq(k4.java:3730)
    at com.ibm.db2.jcc.am.k4.a(k4.java:4609)
    at com.ibm.db2.jcc.am.k4.b(k4.java:4182)
    at com.ibm.db2.jcc.am.k4.bd(k4.java:780)
    at com.ibm.db2.jcc.am.k4.executeQuery(k4.java:745)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:304)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

This is true in general for any DB2 queries that use COALESCE and are trying to run inside Spark JDBC.

Is there any way with which we can run queries using COALESCE inside Spark JDBC.

Body:
You are renaming column 1 (which does not exist) to USER_ID.

I am not familiar with DB2 but will need to set the column name in your SQL statement:

.option("dbtable", "(SELECT COALESCE(USER_ID,0) AS USER_ID FROM DBNFMSXR.ENTITLE_USER) AS X")

Omit the .withColumnRenamed("1", "USER_ID") and this will work.


问:
Path Based Routing with Nginx Controller not working
I have been trying my Nginx Path-Based routing to work, however, after spending almost 4 hours, I am failed to understand, why is it not working. I have gone through almost every possible answer on StackOverflow before anyone downgrades my question, but none worked for me.

So here what I did:

I installed nginx-ingress using Helm 3 (https://docs.nginx.com/nginx-ingress-controller/installation/installation-with-helm/) in a separate namespace - nginx-test:

helm install my-release nginx-stable/nginx-ingress

A version of the ingress controller (https://hub.helm.sh/charts/nginx-edge/nginx-ingress):

```<code>$ POD_NAME=$(kubectl get pods -l app=nginx-controller-nginx-ingress -o jsonpath='{.items[0].metadata.name}')
$
$ kubectl exec -it $POD_NAME -- /nginx-ingress --version
Version=edge GitCommit=50e908aa
$
</code>```

There are 2 basic nginx deployments, 2 services already configured in the same namespace, and working fine when I configure host-based routing for them.

Below one works fine for me (when I define host-based routing and get the required page index.html when I run both individual URLs):

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - host: nginx1.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx1
          servicePort: 80

  - host: nginx2.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx2
          servicePort: 80
</code>```

Now I wanted to achieve the same result using Path-Based routing, where there will be 1 URL and 2 Paths /nginx1 (pointing to nginx1 service) and /nginx2 (pointing to nginx2 service). So I configured the below ingress resource (and many permutations and combinations I applied based on different examples on internet), none of them worked for me.

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-path-based
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: nginx.example.com
    http:
      paths:
      - path: /nginx1
        backend:
          serviceName: nginx1
          servicePort: 80
      - path: /nginx2
        backend:
          serviceName: nginx2
          servicePort: 80
</code>```

When I access services directly, it works fine, however when I try to access - curl http://nginx.example.com/nginx1 or curl http://nginx.example.com/nginx2 - I get 404 Not Found error.

I was expecting to receive the same response which I was getting for Host-Based routing. But it does not seem to work.

答:
So finally I had to install the controller using manifests, instead of helm charts (edge version).

I installed it from here (https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal), changed NodePort to LoadBalancer to get a LoadBalancer IP. I am using MetalLB on BareMetal.

```<code>$ POD_NAME=$(kubectl get pods -n $POD_NAMESPACE -l app.kubernetes.io/component=controller -o jsonpath='{.items[0].metadata.name}')
$ kubectl exec -it $POD_NAME -n $POD_NAMESPACE -- /nginx-ingress-controller --version
-------------------------------------------------------------------------------
NGINX Ingress controller
  Release:       0.32.0
  Build:         git-446845114
  Repository:    https://github.com/kubernetes/ingress-nginx
  nginx version: nginx/1.17.10

-------------------------------------------------------------------------------

$
</code>```

My Ingress resource looks like the same which I posted while asking the question.

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-path-based
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - host: nginx.gofork8s.com
    http:
      paths:
      - path: /nginx1
        backend:
          serviceName: nginx1
          servicePort: 80
      - path: /nginx2
        backend:
          serviceName: nginx2
          servicePort: 80
</code>```

Modified the new LoadBalancer IP in /etc/hosts file to get the domain work.

```<code>192.168.0.1 nginx.example.com
</code>```

Now I am able to access - http://nginx.example.com/nginx1 and http://nginx.example.com/nginx2.

I hope it will help someone. I still need to figure out settings with Helm Charts.

Body:
I have been trying my Nginx Path-Based routing to work, however, after spending almost 4 hours, I am failed to understand, why is it not working. I have gone through almost every possible answer on StackOverflow before anyone downgrades my question, but none worked for me.

So here what I did:

I installed nginx-ingress using Helm 3 (https://docs.nginx.com/nginx-ingress-controller/installation/installation-with-helm/) in a separate namespace - nginx-test:

helm install my-release nginx-stable/nginx-ingress

A version of the ingress controller (https://hub.helm.sh/charts/nginx-edge/nginx-ingress):

$ POD_NAME=$(kubectl get pods -l app=nginx-controller-nginx-ingress -o jsonpath='{.items[0].metadata.name}')
$
$ kubectl exec -it $POD_NAME -- /nginx-ingress --version
Version=edge GitCommit=50e908aa
$

There are 2 basic nginx deployments, 2 services already configured in the same namespace, and working fine when I configure host-based routing for them.

Below one works fine for me (when I define host-based routing and get the required page index.html when I run both individual URLs):

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - host: nginx1.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx1
          servicePort: 80

  - host: nginx2.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx2
          servicePort: 80

Now I wanted to achieve the same result using Path-Based routing, where there will be 1 URL and 2 Paths /nginx1 (pointing to nginx1 service) and /nginx2 (pointing to nginx2 service). So I configured the below ingress resource (and many permutations and combinations I applied based on different examples on internet), none of them worked for me.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-path-based
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: nginx.example.com
    http:
      paths:
      - path: /nginx1
        backend:
          serviceName: nginx1
          servicePort: 80
      - path: /nginx2
        backend:
          serviceName: nginx2
          servicePort: 80

When I access services directly, it works fine, however when I try to access - curl http://nginx.example.com/nginx1 or curl http://nginx.example.com/nginx2 - I get 404 Not Found error.

I was expecting to receive the same response which I was getting for Host-Based routing. But it does not seem to work.

Body:
So finally I had to install the controller using manifests, instead of helm charts (edge version).

I installed it from here (https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal), changed NodePort to LoadBalancer to get a LoadBalancer IP. I am using MetalLB on BareMetal.

$ POD_NAME=$(kubectl get pods -n $POD_NAMESPACE -l app.kubernetes.io/component=controller -o jsonpath='{.items[0].metadata.name}')
$ kubectl exec -it $POD_NAME -n $POD_NAMESPACE -- /nginx-ingress-controller --version
-------------------------------------------------------------------------------
NGINX Ingress controller
  Release:       0.32.0
  Build:         git-446845114
  Repository:    https://github.com/kubernetes/ingress-nginx
  nginx version: nginx/1.17.10

-------------------------------------------------------------------------------

$

My Ingress resource looks like the same which I posted while asking the question.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-path-based
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - host: nginx.gofork8s.com
    http:
      paths:
      - path: /nginx1
        backend:
          serviceName: nginx1
          servicePort: 80
      - path: /nginx2
        backend:
          serviceName: nginx2
          servicePort: 80

Modified the new LoadBalancer IP in /etc/hosts file to get the domain work.

192.168.0.1 nginx.example.com

Now I am able to access - http://nginx.example.com/nginx1 and http://nginx.example.com/nginx2.

I hope it will help someone. I still need to figure out settings with Helm Charts.


问:
How to make a SwiftUI List scroll automatically?
When adding content to my ListView, I want it to automatically scroll down.

I'm using a SwiftUI List, and a BindableObject as Controller. New data is getting appended to the list.

List(chatController.messages, id: \.self) { message in
    MessageView(message.text, message.isMe)
}
```

I want the list to scroll down, as I append new data to the message list. However I have to scroll down manually.

答:
I present other solution getting the UITableView reference using the library Introspect until that Apple improves the available methods.</p>

```<code>struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData
    @State private var tableView: UITableView?
    private var disposables = Set<AnyCancellable>()

    var body: some View {
        NavigationView {
            VStack {
                List(userData.landmarks, id: \.id) { landmark in
                    LandmarkRow(landmark: landmark)
                }
                .introspectTableView { (tableView) in
                    if self.tableView == nil {
                        self.tableView = tableView
                        print(tableView)
                    }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
            .onReceive(userData.$landmarks) { (id) in
                // Do something with the table for example scroll to the bottom
                self.tableView?.setContentOffset(CGPoint(x: 0, y: CGFloat.greatestFiniteMagnitude), animated: false)
            }
        }
    }
}
</code>```

Body:
When adding content to my ListView, I want it to automatically scroll down.

I'm using a SwiftUI List, and a BindableObject as Controller. New data is getting appended to the list.

List(chatController.messages, id: \.self) { message in
    MessageView(message.text, message.isMe)
}

I want the list to scroll down, as I append new data to the message list. However I have to scroll down manually.

Body:
I present other solution getting the UITableView reference using the library Introspect until that Apple improves the available methods.

struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData
    @State private var tableView: UITableView?
    private var disposables = Set<AnyCancellable>()

    var body: some View {
        NavigationView {
            VStack {
                List(userData.landmarks, id: \.id) { landmark in
                    LandmarkRow(landmark: landmark)
                }
                .introspectTableView { (tableView) in
                    if self.tableView == nil {
                        self.tableView = tableView
                        print(tableView)
                    }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
            .onReceive(userData.$landmarks) { (id) in
                // Do something with the table for example scroll to the bottom
                self.tableView?.setContentOffset(CGPoint(x: 0, y: CGFloat.greatestFiniteMagnitude), animated: false)
            }
        }
    }
}


问:
How to turn off logs from winston for jest
Currently I am testing a NodeJS app using jest. Particularly the system looks like this:

NodeJS v13.4.0

Jest 25.4.0

winston@next 3.2.1

When I run tests, I like the log to be ordered. Especially at the first test and then dig into the logs. I know, that jest has the option --silent. Funnily this option does not apply to winston. The source code of winston looks like it is trying to directly write to stdout/err.

Does somebody know, how I can get winston to be silent while tests are running with the --silent option

答:
you can utilize setupFilesAfterEnv jest option, by pointing it to a file that will mock console. for instance

add this to jest.config.js:

{
  ...
  setupFilesAfterEnv: ["./jest.setup.js"],
  ...
}
```

<p>then create a file <code>jest.setup.js</code></p>

<pre class="lang-js prettyprint-override"><code>global.beforeAll(() => {
  console.error = jest.fn().mockImplementation(() => {});
  console.info = jest.fn().mockImplementation(() => {});
  console.log = jest.fn().mockImplementation(() => {});
});

</code>```

The source code of winston looks like it is trying to directly write to stdout/err.

note that, since you configured winston to print to stdout\stderr, so the following advise above should do the trick. of course, you might wish to add an additional check for the --silent flag

otherwise, you can have a condition to silence winston by utilizing the silent property of winston transport

silent: If true, all logs are suppressed

Body:
you can utilize setupFilesAfterEnv jest option, by pointing it to a file that will mock console. for instance

add this to jest.config.js:

{
  ...
  setupFilesAfterEnv: ["./jest.setup.js"],
  ...
}

then create a file jest.setup.js

global.beforeAll(() => {
  console.error = jest.fn().mockImplementation(() => {});
  console.info = jest.fn().mockImplementation(() => {});
  console.log = jest.fn().mockImplementation(() => {});
});

The source code of winston looks like it is trying to directly write to stdout/err.

note that, since you configured winston to print to stdout\stderr, so the following advise above should do the trick. of course, you might wish to add an additional check for the --silent flag

otherwise, you can have a condition to silence winston by utilizing the silent property of winston transport

silent: If true, all logs are suppressed


问:
ASP.NET Core transient DbContext

I have multiple hosted services each working with the database. I was getting the DbConcurrencyException, since all the hosted services were using the same instance of the dbContext simultaneously (at the start of the application).

I've resolved this issue by changing the lifetime of the dbContext from scoped to transient. What did I really change by this? Will the application connect and disconnect from the database each time I work with the dbContext? If not, is there any other issue?

答:
IHostedService or BackgroundService are singletons. Also, by default DBContext (when you run AddDbContext) is scoped service. So in each hosted service, you need to open a scope using IServiceScopeFactory. Like this:

```<code>using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>;
</code>```

Regarding your question about what it has changed when you registered it as transient. Each time you inject and call DBContext it will instantiate a new DbContext. When the service is scoped, during one scope if you are going to call DBContext multiple times, you will get the same instance of DBContext, which will improve performance, so maybe this is what you need?

Title: ASP.NET Core transient DbContext

Body:
IHostedService or BackgroundService are singletons. Also, by default DBContext (when you run AddDbContext) is scoped service. So in each hosted service, you need to open a scope using IServiceScopeFactory. Like this:

using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>;

Regarding your question about what it has changed when you registered it as transient. Each time you inject and call DBContext it will instantiate a new DbContext. When the service is scoped, during one scope if you are going to call DBContext multiple times, you will get the same instance of DBContext, which will improve performance, so maybe this is what you need?


问:
How do you position Material UI Popper in the bottom right corner of the browser?
I'm using Material UI v4.9.1. They have a Popper React component, based on Popper.js v1.14.1.

https://material-ui.com/api/popper

https://popper.js.org/docs/v1

I'm trying to render a small square card on the bottom right corner of my browser.

With plain CSS, I think I would have to do this.

.card {
    position: 'fixed';
    bottom: 0;
    right: 0;
}
```

<p>I was trying to do that with the <code>Popper</code> component, but I'm not sure how. This is what I have now.</p>

```<Popper
    open={anchor !== null}
    placement="bottom-end"
    anchorEl={anchor}
    popperOptions={{positionFixed: true}}
    modifiers={{
        // I think I need some modifier?...
    }}
>
    {/* card component */}
</Popper>
```

<p>I'm setting <code>anchor = document.body</code> when the user clicks a button. I've also set</p>

<pre class="lang-css prettyprint-override"><code>html, body {
    width: 100%;
}
</code>```

in my root index.html.

However, when the Popper appears it's in the top right corner. The div has this style set.

position: fixed;
top: 0px;
left: 0px;
transform: translate3d(1164px, 5px, 0px);
will-change: transform;
```

What am I missing?

答:
Just remove anchorEl={anchor} prop or set it to undefined, popper content will be child of  tag, please double check disablePortal prop (default is false) (follow official document: https://material-ui.com/api/popper/#props).

Hope this help!

Body:
I'm using Material UI v4.9.1. They have a Popper React component, based on Popper.js v1.14.1.

https://material-ui.com/api/popper

https://popper.js.org/docs/v1

I'm trying to render a small square card on the bottom right corner of my browser.

With plain CSS, I think I would have to do this.

.card {
    position: 'fixed';
    bottom: 0;
    right: 0;
}

I was trying to do that with the Popper component, but I'm not sure how. This is what I have now.

<Popper
    open={anchor !== null}
    placement="bottom-end"
    anchorEl={anchor}
    popperOptions={{positionFixed: true}}
    modifiers={{
        // I think I need some modifier?...
    }}
>
    {/* card component */}
</Popper>

I'm setting anchor = document.body when the user clicks a button. I've also set

html, body {
    width: 100%;
}

in my root index.html.

However, when the Popper appears it's in the top right corner. The div has this style set.

position: fixed;
top: 0px;
left: 0px;
transform: translate3d(1164px, 5px, 0px);
will-change: transform;

What am I missing?

Body:
Just remove anchorEl={anchor} prop or set it to undefined, popper content will be child of <body> tag, please double check disablePortal prop (default is false) (follow official document: https://material-ui.com/api/popper/#props).

Hope this help!