问:
How do I set a proxy for firefox using Selenium webdriver with Java?
```<code>System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
    Proxy p = new Proxy();
    p.setSocksProxy("83.209.94.87:35923");
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(CapabilityType.PROXY, p);
    WebDriver driver = new FirefoxDriver(cap);
    driver.get("https://www.google.com.au");
</code>```

This code is inside the main method. When I run this code, firefox is launched but the google url isn't followed and the proxy is not set to the one I specify in the code above. How can I fix this?

```<code>public static void main(String[] args) throws InterruptedException, IOException, UnsupportedEncodingException {
    while (true) {
    System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
    WebDriver driver;
    String PROXY = "83.209.94.87:35923";
      //Bellow given syntaxes will set browser proxy settings using DesiredCapabilities.
      Proxy proxy = new Proxy();
      proxy.setAutodetect(false);
      proxy.setProxyType(Proxy.ProxyType.MANUAL);
      proxy.setSocksProxy(PROXY);
      DesiredCapabilities cap = new DesiredCapabilities();
      cap.setCapability(CapabilityType.PROXY, proxy);
      //Use Capabilities when launch browser driver Instance.
      driver = new FirefoxDriver(cap);`
</code>```

答:
you can set proxy details with credentials here in your automation code as above answers explained  but another way to do it without sharing your details in your java or python code with firefox profile.

firefox provides profiles, we can create profile for every user and customize it for proxy ,bookmarks etc.

windows user : open run(win+R) and type 'firefox -p'

linux user : run command 'firefox -p'

1- it will open a dialog box where you can create your profile then  select that profile and open firefox.

2- open a new tab and search 'about:config' .accept the Risk and Continue then click on show all

3-here you can search and set all the property

example:

network.proxy.type     1

 1 for Manually

2 for Automatic proxy

for Manuall proxy -

property                     value

network.proxy.http                    your proxy ip

network.proxy.http_port                   port number

network.proxy.ssl                      your proxy ip

network.proxy.ssl_port                  port number

network.proxy.ftp                  your proxy ip

network.proxy.ftp_port                  port number

(to find your profile name )

Linux :  cd .mozilla/firefox/

windows: Press. +R on the keyboard. A Run dialog will open.
         Type in: %APPDATA%\Mozilla\Firefox\Profiles\
         Click OK. A window will open containing profile folders
now load this profile in java code

```<code>FirefoxOptions options = new FirefoxOptions();
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
FirefoxProfile profile=new FirefoxProfile(new File("path of your profile"));
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
System.setProperty("webdriver.gecko.driver", "path of gecko driver");
driver.get("url");
</code>```

Body:
System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
    Proxy p = new Proxy();
    p.setSocksProxy("83.209.94.87:35923");
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(CapabilityType.PROXY, p);
    WebDriver driver = new FirefoxDriver(cap);
    driver.get("https://www.google.com.au");

This code is inside the main method. When I run this code, firefox is launched but the google url isn't followed and the proxy is not set to the one I specify in the code above. How can I fix this?

public static void main(String[] args) throws InterruptedException, IOException, UnsupportedEncodingException {
    while (true) {
    System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
    WebDriver driver;
    String PROXY = "83.209.94.87:35923";
      //Bellow given syntaxes will set browser proxy settings using DesiredCapabilities.
      Proxy proxy = new Proxy();
      proxy.setAutodetect(false);
      proxy.setProxyType(Proxy.ProxyType.MANUAL);
      proxy.setSocksProxy(PROXY);
      DesiredCapabilities cap = new DesiredCapabilities();
      cap.setCapability(CapabilityType.PROXY, proxy);
      //Use Capabilities when launch browser driver Instance.
      driver = new FirefoxDriver(cap);`

Body:
you can set proxy details with credentials here in your automation code as above answers explained  but another way to do it without sharing your details in your java or python code with firefox profile.

firefox provides profiles, we can create profile for every user and customize it for proxy ,bookmarks etc.

windows user : open run(win+R) and type 'firefox -p'

linux user : run command 'firefox -p'

1- it will open a dialog box where you can create your profile then  select that profile and open firefox.

2- open a new tab and search 'about:config' .accept the Risk and Continue then click on show all

3-here you can search and set all the property

example:

network.proxy.type     1

 1 for Manually

2 for Automatic proxy

for Manuall proxy -

property                     value

network.proxy.http                    your proxy ip

network.proxy.http_port                   port number

network.proxy.ssl                      your proxy ip

network.proxy.ssl_port                  port number

network.proxy.ftp                  your proxy ip

network.proxy.ftp_port                  port number

(to find your profile name )

Linux :  cd .mozilla/firefox/

windows: Press. +R on the keyboard. A Run dialog will open.
         Type in: %APPDATA%\Mozilla\Firefox\Profiles\
         Click OK. A window will open containing profile folders
now load this profile in java code

FirefoxOptions options = new FirefoxOptions();
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
FirefoxProfile profile=new FirefoxProfile(new File("path of your profile"));
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
System.setProperty("webdriver.gecko.driver", "path of gecko driver");
driver.get("url");


来源: stackexchange

问:
How to create an interface for object and array of objects in Angular 8 and type script?
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

```<code>export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}
</code>```

Sample API response like this

```<code>{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}
</code>```

答:
what you have provided in this._erateColumn.next(columnList) method is columnList. And somehow columnList seems to be a single object of the interface ErateColumn, While your BehaviorSubject has type array of ErateColumn. Change that to ErateColumn or provide array in this._erateColumn.next(columnList) method for your code to work.

EDIT

According to the new screenshot of yours, it says property categories is missing so either make it optional like this

```<code>export interface ErateColumn {
  categories?:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}
</code>```

or provide categories.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

Sample API response like this

{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}

Body:
what you have provided in this._erateColumn.next(columnList) method is columnList. And somehow columnList seems to be a single object of the interface ErateColumn, While your BehaviorSubject has type array of ErateColumn. Change that to ErateColumn or provide array in this._erateColumn.next(columnList) method for your code to work.

EDIT

According to the new screenshot of yours, it says property categories is missing so either make it optional like this

export interface ErateColumn {
  categories?:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

or provide categories.


问:
Trying to get property of non-object from blade view in laravel
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

```<code>  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}
</code>```

My controller

```<code>public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}
</code>```

my blade table that i want to display

```<code>    <tbody>
             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

              <tr>

       <td>{{ $user->ID }}</td>
       <td>{{ $user->NICK_NAME }}</td>
       <td>{{ $user->PWD_INVALID_HIT }}</td>

        </tr>
@endforeach
</code>```

dd($user)

```<code>array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]
</code>```

How do i display data in table

答:
For readability:

But really, I probably wouldn't do that extra foreach loop.

I think your controller method should be more like:

```<code>public function index()
{
        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());
         $paginationRecord = CollectionPaginate::paginate($content['data'], count($content), '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}
</code>```

Actually your blade will need to change to this:

```<code><tbody>
@foreach($paginationRecord as $i=>$user)
   @php
     $currentRecordno = 1;
   @endphp
   <tr>
       <td>{{ $user['ID'] }}</td>
       <td>{{ $user['NICK_NAME'] }}</td>
       <td>{{ $user['PWD_INVALID_HIT'] }}</td>
   </tr>
@endforeach
</code>```

Body:
I try to display my pagination data to database ...My pagination data was from json that i already decode .....i was able to pass to my pagination data to view but not able to display in table
....
This is my error from blade view

Trying to get property of non-object

my result pagination

  LengthAwarePaginator {#4177 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#4169 ▼
        #items: array:1 [▼
          "data" => array:852 [▼
            0 => {#624 ▶}
            1 => {#623 ▶}
            2 => {#628 ▼
              +"ID": "cust1"
              +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
              +"NICK_NAME": "CUST1"
              +"PWD_INVALID_HIT": "0"
              +"PWD_CREATE_DT": "2019/07/22 15:57:15"
              +"INSTITUTION_ID": "C01"
              +"ACL_ID": "L04"
              +"LOGIN_DT": "2019/07/22 15:57:15"
              +"LOGIN_STS_ID": "N"
              +"STS_ID": "C08"
              +"TYPE_ID": "U00"
              +"UPD_ID": "sufyzasukor"
              +"UPD_DT": "2019/07/22 15:57:15"
              +"EMAIL_ID": "cust1@gmail.com"
              +"PHONE_NO_ID": "0"
              +"HP_ID": "0                        "
              +"CRT_DATE_DELETED": null
              +"irel__com_access_level": {#621 …9}
              +"irel__com_user_types": {#630 …5}
              +"irel__com_status": {#631 …5}
            }
}
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

My controller

public function index()
    {

        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());

         $total = count($content) ;
         $collection = new \Illuminate\Support\Collection($content);
         $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}

my blade table that i want to display

             @foreach($paginationRecord as $i=>$user)
              @php
              $currentRecordno = 1;

              @endphp

       {{ $user->ID }}
       {{ $user->NICK_NAME }}
       {{ $user->PWD_INVALID_HIT }}

@endforeach

dd($user)

array:852 [▼
  0 => array:20 [▶]
  1 => array:20 [▶]
  2 => array:20 [▼
    "ID" => "cust1"
    "PWD" => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
    "NICK_NAME" => "CUST1"
    "PWD_INVALID_HIT" => "0"
    "PWD_CREATE_DT" => "2019/07/22 15:57:15"
    "INSTITUTION_ID" => "C01"
    "ACL_ID" => "L04"
    "LOGIN_DT" => "2019/07/22 15:57:15"
    "LOGIN_STS_ID" => "N"
    "STS_ID" => "C08"
    "TYPE_ID" => "U00"
    "UPD_ID" => "sufyzasukor"
    "UPD_DT" => "2019/07/22 15:57:15"
    "EMAIL_ID" => "cust1@gmail.com"
    "PHONE_NO_ID" => "0"
    "HP_ID" => "0                        "
    "CRT_DATE_DELETED" => null
    "irel__com_access_level" => array:9 [ …9]
    "irel__com_user_types" => array:5 [ …5]
    "irel__com_status" => array:5 [ …5]

How do i display data in table

Body:
For readability:

But really, I probably wouldn't do that extra foreach loop.

I think your controller method should be more like:

public function index()
{
        $response =  $this->client->get('getUserIndex')->getBody();
         $content = json_decode($response->getContents());
         $paginationRecord = CollectionPaginate::paginate($content['data'], count($content), '15');

         return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord]);

}

Actually your blade will need to change to this:

<tbody>
@foreach($paginationRecord as $i=>$user)
   @php
     $currentRecordno = 1;
   @endphp
   <tr>
       <td>{{ $user['ID'] }}</td>
       <td>{{ $user['NICK_NAME'] }}</td>
       <td>{{ $user['PWD_INVALID_HIT'] }}</td>
   </tr>
@endforeach


问:
PHP:PCRE: How to replace repeatable char
for example I have following string:

```<code>a_b__c___d____e
</code>```

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

```<code>source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e
</code>```

or

```<code>source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f
</code>```

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

答:
Here is another one using the e modifier:

```<code> $str = 'a_b__c___d____e_____f';
 echo preg_replace('/_{4,}/e', 'str_repeat("-", strlen("$0"))', $str);
</code>```

Replace 4 by the number you need. Or as function:

```<code>function repl($str, $char, $times) {
    $char = preg_quote($char, '/');
    $times = preg_quote($times, '/');
    $pattern = '/' . $char . '{' . $times . ',}/e',
    return preg_replace($pattern, 'str_repeat("-", strlen("$0"))', $str);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
for example I have following string:

a_b__c___d____e

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e

or

source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

Body:
Here is another one using the e modifier:

 $str = 'a_b__c___d____e_____f';
 echo preg_replace('/_{4,}/e', 'str_repeat("-", strlen("$0"))', $str);

Replace 4 by the number you need. Or as function:

function repl($str, $char, $times) {
    $char = preg_quote($char, '/');
    $times = preg_quote($times, '/');
    $pattern = '/' . $char . '{' . $times . ',}/e',
    return preg_replace($pattern, 'str_repeat("-", strlen("$0"))', $str);
}


问:
Can not log in Elementary after install ubuntu 18.04 (dual boot)
I am new to Ubuntu 18.04. It has been a long time that I have not updated anything new on my current OS which is Loki (interestingly, besides Loki does not allow ppl to upgrade Juno).

For some reasons, I have to install another Linux OS on my machine, which is ubuntu 18.04 - the minimal installation. Although everything works perfectly to Ubuntu, it makes me cannot log in to my main OS.

Description of an issue: After selecting a boot of elementary, I log in my account on a log-in page of Elementary. It does not show anything else and move back to the log-in. Another try with a guest account (with no password), still the same problem.

Because most of my data and work in Elementary, I have to find a way to solve this problem. Is there anyone here giving me a hand? Thank you very much.

答:
I ran into same problem once.

Login into tty mode by Ctrl+Shift+F1,and enter:

sudo dpkg --configure -a

sudo apt-get install ecryptfs-utils

sudo reboot

And I was able to login


问:
JavaFX Scene Builder path in Ubuntu
Can anyone please tell me where I can find the path to the correct files for Scene Builder on Ubuntu to get it linked in my preferences with Eclipse IDE.</p>

答: select these path in your IDE opt/SceneBuilder

Title: JavaFX Scene Builder path in Ubuntu


问:
Can Admob be integrated in Android TV
I have an Android app that supports both Mobile phones and Android TV. On few different blog discussions i heard some of devs got their Admob accounts banned for putting Ads in TV app. So i have two questions in this regard:

Since my App supports both mediums (TV & Phone), if i put Ads for Phone App only and doesn't show them on TV , Will that harm my Play or Admob account in any way?

2.Can we put Ads in our TV APP ? Otherwise how do we monetize ?

P.S: I know this question has been asked before long ago, I couldn't find any fresh questions on this.

答:
Yes, you can integrate Admob in Android TV. Make sure that your implementation should be compliant to the Admob policy.

Follow below question link for more details:
Admob for Android TV app

Title: Can Admob be integrated in Android TV


问:
How to pass variable to later in program / Inputting double to dialog box
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

```<code>void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
</code>```

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

答:
For the 2089881670 problem, you should initialize your variable like this :

double variable=0;

For the variable created somewhere and used far far away, you could use a global/static variable (sic), like this :

```<code>static double variable;

void function()
{
char buf[256] = "400";
   sprintf( buf, "%d", variable);
   #ifdef WIN32
   edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
   #endif
   variable = atof(buf);
}
</code>```

Body:
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

Body:
For the 2089881670 problem, you should initialize your variable like this :

double variable=0;

For the variable created somewhere and used far far away, you could use a global/static variable (sic), like this :

static double variable;

void function()
{
char buf[256] = "400";
   sprintf( buf, "%d", variable);
   #ifdef WIN32
   edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
   #endif
   variable = atof(buf);
}


问:
Foreign Keys, Eager Loading, and DTOs (.NET Core 3.1 / Entity Framework Core)

Context

I am building a simple .NET Core API and am having some trouble returning the correct data from my Controllers. I foresee having to use DTOs to manage what data is being sent to and from the API, but I am not convinced that I have my EF Core relationships configured properly. What's throwing me for a loop is that the children objects in my models are returning null - I will explain further.

I have two domain models, Player and Match. Each Match has four Players, which I believe will require four foreign keys to be created to the same table. The SQL Database that EF Core generates looks just how I envisioned it looking - I have included a screenshot too for more context. I can create Player objects just fine using the API POST method. However, when I create a Match object, using Player Guids (as seen below), querying the newly created Match object from the database doesn't return the Player object in JSON the way I hoped it would; the MatchController returns the Player Guids, but no player information.

Ultimately, I'd like to consistently display Player data for each of the four players in a Match, but I'm not sure what changes to my models or Fluent API would be needed for me to achieve this. I do plan to using AutoMapper to map the domain model objects to DTO model objects in the future, but this current predicament seems like something I should iron out first. I'd be more than happy to provide more information if there's anything else that would allow for better assistance! Any and all help would be sincerely and greatly appreciated! Thanks in advance!

Note: I don't care about having a collection of Matches in my Player model - I only have that included because I thought that was necessary to build the Foreign Key constraints in Entity Framework Core

Models:

Player.cs (Domain model)

public class Player
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    public double Rating { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public ICollection<Match> MatchesOne { get; set; }
    public ICollection<Match> MatchesTwo { get; set; }
    public ICollection<Match> MatchesThree { get; set; }
    public ICollection<Match> MatchesFour { get; set; }
}
```

<p><strong>Match.cs</strong> (Domain model)</p>

<pre class="lang-c# prettyprint-override"><code>public class Match
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public int TeamOneScore { get; set; }
    [Required]
    public int TeamTwoScore { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public Guid PlayerOneId { get; set; }
    public Guid PlayerTwoId { get; set; }
    public Guid PlayerThreeId { get; set; }
    public Guid PlayerFourId { get; set; }

    public Player PlayerOne { get; set; }
    public Player PlayerTwo { get; set; }
    public Player PlayerThree { get; set; }
    public Player PlayerFour { get; set; }
}
</code>```

ApplicationDbContext.cs (Fluent API)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Player>()
        .Property(p => p.Rating)
        .HasDefaultValue(1000);

    modelBuilder.Entity<Player>()
        .Property(p => p.Created)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Player>()
        .Property(p => p.Updated)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Match>()
        .Property(m => m.Created)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Match>()
        .Property(m => m.Updated)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesOne)
        .WithOne(m => m.PlayerOne)
        .HasForeignKey(m => m.PlayerOneId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesTwo)
        .WithOne(m => m.PlayerTwo)
        .HasForeignKey(m => m.PlayerTwoId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesThree)
        .WithOne(m => m.PlayerThree)
        .HasForeignKey(m => m.PlayerThreeId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesFour)
        .WithOne(m => m.PlayerFour)
        .HasForeignKey(m => m.PlayerFourId)
        .OnDelete(DeleteBehavior.NoAction);
}
```

<p><br /></p>

<h2>Controllers:</h2>

<p><strong>PlayerController.cs</strong></p>

<pre class="lang-c# prettyprint-override"><code>[HttpGet]
public async Task<ActionResult<IEnumerable<Player>>> GetPlayers()
{
    return await _context.Players.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Player>> PostPlayer(Player player)
{
    _context.Players.Add(player);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetPlayer), new { id = player.Id }, player);
}
</code>```

MatchController.cs

[HttpGet]
public async Task<ActionResult<IEnumerable<Match>>> GetMatches()
{
    return await _context.Matches.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Match>> PostMatch(Match match)
{
    _context.Matches.Add(match);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetMatch), new { id = match.Id }, match);
}
```

<p><br /></p>

<h2>HTTP Requests</h2>

<p><strong>HTTP POST: PostPlayer (/api/Player)</strong>
<em>Request:</em></p>

<pre class="lang-json prettyprint-override"><code>{
    "Name":"Mike Blart"
}
</code>```

Response:

{
    "id": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
    "name": "Mike Blart",
    "rating": 1000,
    "created": "2020-02-19T14:32:48.8033333",
    "updated": "2020-02-19T14:32:48.8033333",
    "matchesOne": null,
    "matchesTwo": null,
    "matchesThree": null,
    "matchesFour": null
}
```

<p><strong>HTTP POST: PostMatch (/api/Match)</strong>
<em>Request:</em></p>

<pre class="lang-json prettyprint-override"><code>{
    "TeamOneScore":21,
    "TeamTwoScore":13,
    "PlayerOneId":"0589867f-590b-4344-d3e9-08d7b5480646",
    "PlayerTwoId":"0f45247b-1fdb-404a-d3ea-08d7b5480646",
    "PlayerThreeId":"f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
    "PlayerFourId":"d3c022a2-d347-4a9a-d3ec-08d7b5480646"
}
</code>```

Response:

{
    "id": "dfdc2f23-0786-40df-8aa7-08d7b54fd4a1",
    "teamOneScore": 21,
    "teamTwoScore": 13,
    "created": "2020-02-19T15:24:38.7233333",
    "updated": "2020-02-19T15:24:38.7233333",
    "playerOneId": "0589867f-590b-4344-d3e9-08d7b5480646",
    "playerTwoId": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
    "playerThreeId": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
    "playerFourId": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
    "playerOne": null,
    "playerTwo": null,
    "playerThree": null,
    "playerFour": null
}
```

<p><br />
<strong>HTTP GET: GetPlayers (/api/Player)</strong></p>

<pre class="lang-json prettyprint-override"><code>[
    {
        "id": "0589867f-590b-4344-d3e9-08d7b5480646",
        "name": "Merwin Dedrick",
        "rating": 1000,
        "created": "2020-02-19T14:28:44.7966667",
        "updated": "2020-02-19T14:28:44.7966667",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
        "name": "Omar Rupaz",
        "rating": 1000,
        "created": "2020-02-19T14:30:04.4933333",
        "updated": "2020-02-19T14:30:04.4933333",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
        "name": "Aaron Randolph",
        "rating": 1000,
        "created": "2020-02-19T14:32:38.7066667",
        "updated": "2020-02-19T14:32:38.7066667",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
        "name": "Mike Blart",
        "rating": 1000,
        "created": "2020-02-19T14:32:48.8033333",
        "updated": "2020-02-19T14:32:48.8033333",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    }
]
</code>```

HTTP GET: GetMatches (/api/Match)

[
    {
        "id": "ce06237b-a137-47bc-e0b7-08d7b5484c68",
        "teamOneScore": 21,
        "teamTwoScore": 13,
        "created": "2020-02-19T14:33:24.1266667",
        "updated": "2020-02-19T14:33:24.1266667",
        "playerOneId": "0589867f-590b-4344-d3e9-08d7b5480646",
        "playerTwoId": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
        "playerThreeId": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
        "playerFourId": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
        "playerOne": null,
        "playerTwo": null,
        "playerThree": null,
        "playerFour": null
    }
]
```

答:
For you want to show the four players' info when you display one match,you could use Include:

```<code>[HttpGet]
public async Task<ActionResult<IEnumerable<Match>>> GetMatches()
{
    return await _context.Matches.ToListAsync();
}

// GET: api/Matches/5
[HttpGet("{id}")]
public async Task<ActionResult<Match>> GetMatch(Guid id)
{
    var match = await _context.Matches
                    .Include(m => m.PlayerOne)
                    .Include(m => m.PlayerTwo)
                    .Include(m => m.PlayerThree)
                    .Include(m => m.PlayerFour)
                    .Where(m => m.Id == id)
                    .FirstOrDefaultAsync();
    return match;
}

[HttpPost]
public async Task<ActionResult<Match>> PostMatch(Match match)
{
    _context.Matches.Add(match);
    await _context.SaveChangesAsync();

    //change CreatedAtAction to CreatedAtAction...
    return RedirectToAction("GetMatch", new { id = match.Id });
}
</code>```

Result:

```<code>{
    "id": "e35bff4e-1d3a-40db-6da7-08d7b5c7defc",
    "teamOneScore": 21,
    "teamTwoScore": 13,
    "created": "2020-02-20T13:43:54.1066667",
    "updated": "2020-02-20T13:43:54.1066667",
    "playerOneId": "6a35cfd0-b55f-4151-a75f-08d7b5c79d60",
    "playerTwoId": "caa71d4a-1fe5-488a-a760-08d7b5c79d60",
    "playerThreeId": "4c057f8c-9a05-4e33-a761-08d7b5c79d60",
    "playerFourId": "4dd619f2-1680-4bb6-a762-08d7b5c79d60",
    "playerOne": {
        "id": "6a35cfd0-b55f-4151-a75f-08d7b5c79d60",
        "name": "Mike Blart",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:05.94",
        "updated": "2020-02-20T13:42:05.94",
        "matchesOne": [],
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    "playerTwo": {
        "id": "caa71d4a-1fe5-488a-a760-08d7b5c79d60",
        "name": "aaa",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:24.3866667",
        "updated": "2020-02-20T13:42:24.3866667",
        "matchesOne": null,
        "matchesTwo": [],
        "matchesThree": null,
        "matchesFour": null
    },
    "playerThree": {
        "id": "4c057f8c-9a05-4e33-a761-08d7b5c79d60",
        "name": "vvv",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:28.83",
        "updated": "2020-02-20T13:42:28.83",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": [],
        "matchesFour": null
    },
    "playerFour": {
        "id": "4dd619f2-1680-4bb6-a762-08d7b5c79d60",
        "name": "ccc",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:32.86",
        "updated": "2020-02-20T13:42:32.86",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": []
    }
}
</code>```

Note:be sure to install Microsoft.AspNetCore.Mvc.NewtonsoftJson then use the following code:

```<code>services.AddControllers().AddNewtonsoftJson(x =>
              x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
</code>```

Reference: Loading Related Data

Body:
Context

I am building a simple .NET Core API and am having some trouble returning the correct data from my Controllers. I foresee having to use DTOs to manage what data is being sent to and from the API, but I am not convinced that I have my EF Core relationships configured properly. What's throwing me for a loop is that the children objects in my models are returning null - I will explain further.

I have two domain models, Player and Match. Each Match has four Players, which I believe will require four foreign keys to be created to the same table. The SQL Database that EF Core generates looks just how I envisioned it looking - I have included a screenshot too for more context. I can create Player objects just fine using the API POST method. However, when I create a Match object, using Player Guids (as seen below), querying the newly created Match object from the database doesn't return the Player object in JSON the way I hoped it would; the MatchController returns the Player Guids, but no player information.

Ultimately, I'd like to consistently display Player data for each of the four players in a Match, but I'm not sure what changes to my models or Fluent API would be needed for me to achieve this. I do plan to using AutoMapper to map the domain model objects to DTO model objects in the future, but this current predicament seems like something I should iron out first. I'd be more than happy to provide more information if there's anything else that would allow for better assistance! Any and all help would be sincerely and greatly appreciated! Thanks in advance!

Note: I don't care about having a collection of Matches in my Player model - I only have that included because I thought that was necessary to build the Foreign Key constraints in Entity Framework Core

Models:

Player.cs (Domain model)

public class Player
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    public double Rating { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public ICollection<Match> MatchesOne { get; set; }
    public ICollection<Match> MatchesTwo { get; set; }
    public ICollection<Match> MatchesThree { get; set; }
    public ICollection<Match> MatchesFour { get; set; }
}

Match.cs (Domain model)

public class Match
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public int TeamOneScore { get; set; }
    [Required]
    public int TeamTwoScore { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public Guid PlayerOneId { get; set; }
    public Guid PlayerTwoId { get; set; }
    public Guid PlayerThreeId { get; set; }
    public Guid PlayerFourId { get; set; }

    public Player PlayerOne { get; set; }
    public Player PlayerTwo { get; set; }
    public Player PlayerThree { get; set; }
    public Player PlayerFour { get; set; }
}

ApplicationDbContext.cs (Fluent API)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Player>()
        .Property(p => p.Rating)
        .HasDefaultValue(1000);

    modelBuilder.Entity<Player>()
        .Property(p => p.Created)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Player>()
        .Property(p => p.Updated)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Match>()
        .Property(m => m.Created)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Match>()
        .Property(m => m.Updated)
        .HasDefaultValueSql("GETDATE()");

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesOne)
        .WithOne(m => m.PlayerOne)
        .HasForeignKey(m => m.PlayerOneId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesTwo)
        .WithOne(m => m.PlayerTwo)
        .HasForeignKey(m => m.PlayerTwoId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesThree)
        .WithOne(m => m.PlayerThree)
        .HasForeignKey(m => m.PlayerThreeId)
        .OnDelete(DeleteBehavior.NoAction);

    modelBuilder.Entity<Player>()
        .HasMany(p => p.MatchesFour)
        .WithOne(m => m.PlayerFour)
        .HasForeignKey(m => m.PlayerFourId)
        .OnDelete(DeleteBehavior.NoAction);
}

Controllers:

PlayerController.cs

[HttpGet]
public async Task<ActionResult<IEnumerable<Player>>> GetPlayers()
{
    return await _context.Players.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Player>> PostPlayer(Player player)
{
    _context.Players.Add(player);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetPlayer), new { id = player.Id }, player);
}

MatchController.cs

[HttpGet]
public async Task<ActionResult<IEnumerable<Match>>> GetMatches()
{
    return await _context.Matches.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Match>> PostMatch(Match match)
{
    _context.Matches.Add(match);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(GetMatch), new { id = match.Id }, match);
}

HTTP Requests

HTTP POST: PostPlayer (/api/Player)
Request:

{
    "Name":"Mike Blart"
}

Response:

{
    "id": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
    "name": "Mike Blart",
    "rating": 1000,
    "created": "2020-02-19T14:32:48.8033333",
    "updated": "2020-02-19T14:32:48.8033333",
    "matchesOne": null,
    "matchesTwo": null,
    "matchesThree": null,
    "matchesFour": null
}

HTTP POST: PostMatch (/api/Match)
Request:

{
    "TeamOneScore":21,
    "TeamTwoScore":13,
    "PlayerOneId":"0589867f-590b-4344-d3e9-08d7b5480646",
    "PlayerTwoId":"0f45247b-1fdb-404a-d3ea-08d7b5480646",
    "PlayerThreeId":"f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
    "PlayerFourId":"d3c022a2-d347-4a9a-d3ec-08d7b5480646"
}

Response:

{
    "id": "dfdc2f23-0786-40df-8aa7-08d7b54fd4a1",
    "teamOneScore": 21,
    "teamTwoScore": 13,
    "created": "2020-02-19T15:24:38.7233333",
    "updated": "2020-02-19T15:24:38.7233333",
    "playerOneId": "0589867f-590b-4344-d3e9-08d7b5480646",
    "playerTwoId": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
    "playerThreeId": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
    "playerFourId": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
    "playerOne": null,
    "playerTwo": null,
    "playerThree": null,
    "playerFour": null
}

HTTP GET: GetPlayers (/api/Player)

[
    {
        "id": "0589867f-590b-4344-d3e9-08d7b5480646",
        "name": "Merwin Dedrick",
        "rating": 1000,
        "created": "2020-02-19T14:28:44.7966667",
        "updated": "2020-02-19T14:28:44.7966667",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
        "name": "Omar Rupaz",
        "rating": 1000,
        "created": "2020-02-19T14:30:04.4933333",
        "updated": "2020-02-19T14:30:04.4933333",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
        "name": "Aaron Randolph",
        "rating": 1000,
        "created": "2020-02-19T14:32:38.7066667",
        "updated": "2020-02-19T14:32:38.7066667",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    {
        "id": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
        "name": "Mike Blart",
        "rating": 1000,
        "created": "2020-02-19T14:32:48.8033333",
        "updated": "2020-02-19T14:32:48.8033333",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    }
]

HTTP GET: GetMatches (/api/Match)

[
    {
        "id": "ce06237b-a137-47bc-e0b7-08d7b5484c68",
        "teamOneScore": 21,
        "teamTwoScore": 13,
        "created": "2020-02-19T14:33:24.1266667",
        "updated": "2020-02-19T14:33:24.1266667",
        "playerOneId": "0589867f-590b-4344-d3e9-08d7b5480646",
        "playerTwoId": "0f45247b-1fdb-404a-d3ea-08d7b5480646",
        "playerThreeId": "f8b4e13d-0dd0-4ef5-d3eb-08d7b5480646",
        "playerFourId": "d3c022a2-d347-4a9a-d3ec-08d7b5480646",
        "playerOne": null,
        "playerTwo": null,
        "playerThree": null,
        "playerFour": null
    }
]

Body:
For you want to show the four players' info when you display one match,you could use Include:

[HttpGet]
public async Task<ActionResult<IEnumerable<Match>>> GetMatches()
{
    return await _context.Matches.ToListAsync();
}

// GET: api/Matches/5
[HttpGet("{id}")]
public async Task<ActionResult<Match>> GetMatch(Guid id)
{
    var match = await _context.Matches
                    .Include(m => m.PlayerOne)
                    .Include(m => m.PlayerTwo)
                    .Include(m => m.PlayerThree)
                    .Include(m => m.PlayerFour)
                    .Where(m => m.Id == id)
                    .FirstOrDefaultAsync();
    return match;
}

[HttpPost]
public async Task<ActionResult<Match>> PostMatch(Match match)
{
    _context.Matches.Add(match);
    await _context.SaveChangesAsync();

    //change CreatedAtAction to CreatedAtAction...
    return RedirectToAction("GetMatch", new { id = match.Id });
}

Result:

{
    "id": "e35bff4e-1d3a-40db-6da7-08d7b5c7defc",
    "teamOneScore": 21,
    "teamTwoScore": 13,
    "created": "2020-02-20T13:43:54.1066667",
    "updated": "2020-02-20T13:43:54.1066667",
    "playerOneId": "6a35cfd0-b55f-4151-a75f-08d7b5c79d60",
    "playerTwoId": "caa71d4a-1fe5-488a-a760-08d7b5c79d60",
    "playerThreeId": "4c057f8c-9a05-4e33-a761-08d7b5c79d60",
    "playerFourId": "4dd619f2-1680-4bb6-a762-08d7b5c79d60",
    "playerOne": {
        "id": "6a35cfd0-b55f-4151-a75f-08d7b5c79d60",
        "name": "Mike Blart",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:05.94",
        "updated": "2020-02-20T13:42:05.94",
        "matchesOne": [],
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": null
    },
    "playerTwo": {
        "id": "caa71d4a-1fe5-488a-a760-08d7b5c79d60",
        "name": "aaa",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:24.3866667",
        "updated": "2020-02-20T13:42:24.3866667",
        "matchesOne": null,
        "matchesTwo": [],
        "matchesThree": null,
        "matchesFour": null
    },
    "playerThree": {
        "id": "4c057f8c-9a05-4e33-a761-08d7b5c79d60",
        "name": "vvv",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:28.83",
        "updated": "2020-02-20T13:42:28.83",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": [],
        "matchesFour": null
    },
    "playerFour": {
        "id": "4dd619f2-1680-4bb6-a762-08d7b5c79d60",
        "name": "ccc",
        "rating": 1000.0,
        "created": "2020-02-20T13:42:32.86",
        "updated": "2020-02-20T13:42:32.86",
        "matchesOne": null,
        "matchesTwo": null,
        "matchesThree": null,
        "matchesFour": []
    }
}

Note:be sure to install Microsoft.AspNetCore.Mvc.NewtonsoftJson then use the following code:

services.AddControllers().AddNewtonsoftJson(x =>
              x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

Reference: Loading Related Data


问:
Is there a shorter way to write this inline if?
Hey guys is there a shorter way to write this line.

```<code>int objectID = jsonObject != null && jsonObject.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

//jsonObject.ObjectID is int?
</code>```

Can u use a null coalesce to check null and > 0?

答:
```<code>int objectID = jsonObject?.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

</code>```

Body:
Hey guys is there a shorter way to write this line.

int objectID = jsonObject != null && jsonObject.ObjectID.HasValue && jsonObject.ObjectID.Value > 0 ? jsonObject.ObjectID.Value : defaultObject.ObjectID;

//jsonObject.ObjectID is int?

Can u use a null coalesce to check null and > 0?


问:
Send and Extract zip file to azure VM using powershell
I am trying to send and extract the zip file to azure VM but unable make the connection to the remote Azure VM.

Code

```<code>$cred = Get-Credential
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session
</code>```

Error

```<code>New-PSSession : [xx.xx.xxx.xxx] Connecting to remote server xx.xx.xxx.xxx
failed with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the
following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
At line:4 char:12
+ $session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' - ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:Re
   moteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
</code>```

Below is the output when i run 'winrm quickconfig' command on azure VM

```<code>WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
</code>```

When I run the 'Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-admin'

```<code>Enter-PSSession : Connecting to remote server LoadTestVm failed with the following error
message : The WinRM client cannot process the request because the server name cannot be
resolved. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (LoadTestVm:String) [Enter-PSSession], PSRem
   otingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed
</code>```

答:
WINRM will run on either ports 5985 and 5986. The port 5985 is for HTTP and 5986 is for HTTPS. By default, it uses port 5985 if you have not specified it with -port. You should specify port 5985 instead of 3389, also enable it in your NSG if you have.  So you could run Enter-PSSession -ComputerName "PublicIPaddress of VM" -Port 5985 -Credential $cred.

This works on my side.

```<code>Copy-Item -Path D:\nancy\4.zip -Destination C:\ –ToSession $session

Invoke-Command -Session $session -ScriptBlock { Expand-Archive -Path C:\4.zip -DestinationPath C:\ }
</code>```

More references:

https://www.assistanz.com/access-azure-windows-vm-through-powershell/

https://geekdudes.wordpress.com/2016/11/16/enabling-remote-powershell-connection-to-azure-virtual-machine/

https://mohitgoyal.co/2016/11/10/enable-powershell-remoting-on-azure-rm-virtual-machines/

Body:
I am trying to send and extract the zip file to azure VM but unable make the connection to the remote Azure VM.

Code

$cred = Get-Credential
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session

Error

New-PSSession : [xx.xx.xxx.xxx] Connecting to remote server xx.xx.xxx.xxx
failed with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the
following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
At line:4 char:12
+ $session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' - ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:Re
   moteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed

Below is the output when i run 'winrm quickconfig' command on azure VM

WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

When I run the 'Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-admin'

Enter-PSSession : Connecting to remote server LoadTestVm failed with the following error
message : The WinRM client cannot process the request because the server name cannot be
resolved. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (LoadTestVm:String) [Enter-PSSession], PSRem
   otingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Body:
WINRM will run on either ports 5985 and 5986. The port 5985 is for HTTP and 5986 is for HTTPS. By default, it uses port 5985 if you have not specified it with -port. You should specify port 5985 instead of 3389, also enable it in your NSG if you have.  So you could run Enter-PSSession -ComputerName "PublicIPaddress of VM" -Port 5985 -Credential $cred.

This works on my side.

Copy-Item -Path D:\nancy\4.zip -Destination C:\ –ToSession $session

Invoke-Command -Session $session -ScriptBlock { Expand-Archive -Path C:\4.zip -DestinationPath C:\ }

More references:

https://www.assistanz.com/access-azure-windows-vm-through-powershell/

https://geekdudes.wordpress.com/2016/11/16/enabling-remote-powershell-connection-to-azure-virtual-machine/

https://mohitgoyal.co/2016/11/10/enable-powershell-remoting-on-azure-rm-virtual-machines/


问:
Cannot find AddHealthChecks().AddUrlGroup() not found on .NET Core 2.2
I am trying to health check an endpoint in .NET Core using Microsoft.Extensions.Diagnostics.HealthChecks. Most of the samples code i found is like below

```<code>services.AddHealthChecks()
            .AddUrlGroup(new Uri("** API 1 ENDPOINT **"), "API 1");
</code>```

But i am getting reference error for same telling
IHealthChecksBuilder' does not contain a definition for 'AddUrlGroup' and no accessible extension method 'AddUrlGroup' accepting a first argument of type 'IHealthChecksBuilder' could be found

Is there any other reference for AddUrlGroup or it is not available in .net core 2.2?

答:
Install below NuGet Package will solve your issue

AspNetCore.HealthChecks.Uris

Install-Package AspNetCore.HealthChecks.Uris -v 2.2

Body:
I am trying to health check an endpoint in .NET Core using Microsoft.Extensions.Diagnostics.HealthChecks. Most of the samples code i found is like below

services.AddHealthChecks()
            .AddUrlGroup(new Uri("** API 1 ENDPOINT **"), "API 1");

But i am getting reference error for same telling
IHealthChecksBuilder' does not contain a definition for 'AddUrlGroup' and no accessible extension method 'AddUrlGroup' accepting a first argument of type 'IHealthChecksBuilder' could be found

Is there any other reference for AddUrlGroup or it is not available in .net core 2.2?


问:
keep session connected in a local shiny app
I made a simple desktop application using shiny package mainly for its UI, but there is a problem:

After using shiny::runApp() to start my simple application in Windows desktop (localhost) with a long term task at the back-end, I noticed that the task will be shutdown after 6-7 hours regardless whether it has been completed. There is no any error (or warning) message, although I keep web browser (Chrome) open all the time.

I suspect that this is because there is some kind of max connection time for each session, but I can't find it in the reference manual.

I'm just wondering if anyone knows how can I keep my back-end long term task running forever? Or how can I change setting for the max connection time for the session?

Note: this is not in the Shiny server, but a simple R shiny package.

many thanks

答:
after doing some research, I found a way, although it might be not the correct way or use-case for this.

All in all, it solved my problem!

the solution is:
session$allowReconnect( "force" )


问:
from Eclipse to Android phone
I have made a program on eclipse. But how can I get the program from eclipse to my phone? I have a cable because it probably wont make a QR code like appinventor does huh. How do i install my app on there? </p>

答: You just have to allow the device to accept nonsigned apps and USB debugging (change this in your device's app configuration). Then, if you have the drivers (you can install them within your AVD), you can just run the app from Eclipse in your phone. </p>

Title: from Eclipse to Android phone


问:
Python Flask - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte
When I run a code here is an error
Python files are on the USB flash drive
It is an Error </p>

```<code>Traceback (most recent call last):
  File "e:/1/test.py", line 15, in <module>
    app.run(port=8080, host='127.0.0.1')
  File "E:\python\lib\site-packages\flask\app.py", line 990, in run
    run_simple(host, port, self, **options)
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 1052, in run_simple
    inner()
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 996, in inner
    srv = make_server(
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 847, in make_server
    return ThreadedWSGIServer(
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 740, in __init__
    HTTPServer.__init__(self, server_address, handler)
  File "E:\python\lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "E:\python\lib\http\server.py", line 139, in server_bind
    self.server_name = socket.getfqdn(host)
  File "E:\python\lib\socket.py", line 756, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte
</code>```

答: just need to rename the computer to the english symbols</p>

Body:
When I run a code here is an error
Python files are on the USB flash drive
It is an Error

Traceback (most recent call last):
  File "e:/1/test.py", line 15, in <module>
    app.run(port=8080, host='127.0.0.1')
  File "E:\python\lib\site-packages\flask\app.py", line 990, in run
    run_simple(host, port, self, **options)
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 1052, in run_simple
    inner()
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 996, in inner
    srv = make_server(
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 847, in make_server
    return ThreadedWSGIServer(
  File "E:\python\lib\site-packages\werkzeug\serving.py", line 740, in __init__
    HTTPServer.__init__(self, server_address, handler)
  File "E:\python\lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "E:\python\lib\http\server.py", line 139, in server_bind
    self.server_name = socket.getfqdn(host)
  File "E:\python\lib\socket.py", line 756, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte


问:
How do I write a method that has the same implementation for multiple kinds of objects (Java)?
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

```<code>public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...
</code>```

答:
What I think is that the isStrongAgainst() function can be refined more.
It would better to make an implementation of isType() in such a way that it returns true if the opponent is weaker than us.

This can then be used in the function isStrongAgainst() directly in its return statement.

Best

PS: I am in class right now and I will give a more detailed answer after I’m over with it, till then if possible try to get some idea of what I have said.

Body:
I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.

The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?

public interface TypeMatch<T> {
    boolean isType(Type t);
    default boolean isStrongAgainst(Pokemon opponent){
        if(T.isType(Type.NORMAL)){
            return false;
        }
        if(T.isType(Type.WATER)){
            return opponent.isType(Type.FIRE) ||
                    opponent.isType(Type.ROCK) ||
                    opponent.isType(Type.GROUND);
        } //etc...


问:
PyRun_String returns a NoneType object
I'm writing a base64 function in c++.I want to use python to do the encode and returns the result to my c++ program.Here is my code:

string EncodeBase64(string str)
{
    Py_Initialize();
    PyObject* ret1 = NULL;
    PyObject* ret2 = NULL;
    PyObject* main = PyImport_AddModule("__main__");
    PyObject* _g = PyModule_GetDict(main);
    PyObject* _l = PyDict_New();
    string py = "str(base64.b64encode('" + str + "'.encode('utf-8')), 'utf-8')";
    string pyb = "base64.b64encode('" + str + "'.encode('utf-8'))";
    char* rec = new char[8192];
    cout << "Request 1: " << py << endl;
    cout << "Request 2: " << pyb << endl;
    PyRun_SimpleString("import base64");
    ret1 = PyRun_String(py.c_str(), Py_file_input, _g, _l);
    main = PyImport_AddModule("__main__");
    _g = PyModule_GetDict(main);
    _l = PyDict_New();
    ret2 = PyRun_String(pyb.c_str(), Py_file_input, _g, _l);
    if (!ret1)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 1: " << ret1->ob_type->tp_name << endl;
    }
    if (!ret2)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 2: " << ret1->ob_type->tp_name << endl;
    }
    Py_Finalize();
    return "";
}
```

<p>I input a string "123456",and the program outputs this:</p>

```Request 1: str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
Request 2: base64.b64encode('123456'.encode('utf-8'))
Type of Return Value 1: NoneType
Type of Return Value 2: NoneType
```

<p>I tried to input the request strings to python,is runs fine.The result is as follows:</p>

```C:\Users\15819>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
'MTIzNDU2'
>>> base64.b64encode('123456'.encode('utf-8'))
b'MTIzNDU2'
```

<p>I want to know why does the return value of <code>PyRun_String</code> is <code>NoneType</code> and how to make it return the right value.
My envrionment information:</p>

```System: Windows 10 1909 x64
C++IDE: Visual Studio 2019 Professional
Python version: 3.7.4
Project Config: Release X64
```

答:
Passing a start parameter of Py_file_input is similar in effect to passing 'exec' to the compile built-in; it means run it as if it were a complete module (think of it like asking for the "result" of import modulename; there is no "result").

Only expressions evaluate to a non-trivial/non-None result, not modules or statements, so for any start parameter but Py_eval_input (equivalent to 'eval' mode for compile), the result will always be None (it's only None because they need to return something to distinguish between NULL for failure and something else for success, and the eval mode necessitates a PyObject* return rather than a boolean). If you want to evaluate an expression and get the result, you must use Py_eval_input for your start parameter.

Title: PyRun_String returns a NoneType object

Body:
I'm writing a base64 function in c++.I want to use python to do the encode and returns the result to my c++ program.Here is my code:

string EncodeBase64(string str)
{
    Py_Initialize();
    PyObject* ret1 = NULL;
    PyObject* ret2 = NULL;
    PyObject* main = PyImport_AddModule("__main__");
    PyObject* _g = PyModule_GetDict(main);
    PyObject* _l = PyDict_New();
    string py = "str(base64.b64encode('" + str + "'.encode('utf-8')), 'utf-8')";
    string pyb = "base64.b64encode('" + str + "'.encode('utf-8'))";
    char* rec = new char[8192];
    cout << "Request 1: " << py << endl;
    cout << "Request 2: " << pyb << endl;
    PyRun_SimpleString("import base64");
    ret1 = PyRun_String(py.c_str(), Py_file_input, _g, _l);
    main = PyImport_AddModule("__main__");
    _g = PyModule_GetDict(main);
    _l = PyDict_New();
    ret2 = PyRun_String(pyb.c_str(), Py_file_input, _g, _l);
    if (!ret1)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 1: " << ret1->ob_type->tp_name << endl;
    }
    if (!ret2)
    {
        cout << "Can not get return value 1." << endl;
    }
    else
    {
        cout << "Type of Return Value 2: " << ret1->ob_type->tp_name << endl;
    }
    Py_Finalize();
    return "";
}

I input a string "123456",and the program outputs this:

Request 1: str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
Request 2: base64.b64encode('123456'.encode('utf-8'))
Type of Return Value 1: NoneType
Type of Return Value 2: NoneType

I tried to input the request strings to python,is runs fine.The result is as follows:

C:\Users\15819>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
'MTIzNDU2'
>>> base64.b64encode('123456'.encode('utf-8'))
b'MTIzNDU2'

I want to know why does the return value of PyRun_String is NoneType and how to make it return the right value.
My envrionment information:

System: Windows 10 1909 x64
C++IDE: Visual Studio 2019 Professional
Python version: 3.7.4
Project Config: Release X64


问:
Java regex split on whitespace /not preceded
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

```<code>(?<![,=])\\s+
</code>```

答:
It might be difficult to phrase clean regex splitting logic here.  Instead, I would use a formal pattern matcher here, with the regex pattern:

```<code>[^=\s]+\s*=.*?(?=[^=\s]+\s*=|$)
</code>```

Sample script:

```<code>String input = "x=   2-3   y=3 z=   this,   that";
String pattern = "[^=\\s]+\\s*=.*?(?=[^=\\s]+\\s*=|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("match: " + m.group(0));
}
</code>```

This prints:

```<code>match: x=   2-3
match: y=3
match: z=   this,   that
</code>```

Here is an explanation of the regex pattern:

```<code>[^=\s]+           match a variable
\s*               followed by optional whitespace
=                 match =
.*?               consume everything, until seeing the nearest
(?=
    [^=\s]+\s*=   the next variable followed by =
    |             or
    $             or the end of the input (covers the z= case)
)
</code>```

Body:
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

(?<![,=])\\s+

Body:
It might be difficult to phrase clean regex splitting logic here.  Instead, I would use a formal pattern matcher here, with the regex pattern:

[^=\s]+\s*=.*?(?=[^=\s]+\s*=|$)

Sample script:

String input = "x=   2-3   y=3 z=   this,   that";
String pattern = "[^=\\s]+\\s*=.*?(?=[^=\\s]+\\s*=|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("match: " + m.group(0));
}

This prints:

match: x=   2-3
match: y=3
match: z=   this,   that

Here is an explanation of the regex pattern:

[^=\s]+           match a variable
\s*               followed by optional whitespace
=                 match =
.*?               consume everything, until seeing the nearest
(?=
    [^=\s]+\s*=   the next variable followed by =
    |             or
    $             or the end of the input (covers the z= case)
)


问:
How to set the SelectedValue attribute of Telerik RadComboBox inside the FormTemplate of a RadGrid
I have what I think should be a straightforward question.  I have a RadGrid with FormTemplate editing and AJAX enabled.  One of the fields in the FormTemplate is a RadComboBox filled with U.S. State selections.  I can bind the RadComboBox to the data source to populate all the items, but I'm not able to set the SelectedValue attribute.

This RadComboBox is loaded when the Edit button is clicked for a row on the RadGrid.  A custom FormTemplate is used and the contents of the row being edited are loaded via AJAX.

答:
clear all items of radcombobox initially and then add a new item manually

this is what i do to set new item when i use web service

```<code>     ddl.ClearSelection()
            ddl.Items.Clear()

'below i'm getting the actual value and the text to display
            Using reader As IDataReader = GetClientByClientID(CInt(value))
                If reader.Read Then

'adding the item will show in the dropdown
                    Dim item As New RadComboBoxItem(reader("DisplayName").ToString, reader("ID").ToString)
                    item.Selected = True
                    ddl.Items.Add(item)

'this line will make the combobox text to be displayed correctly
                    ddl.Text = reader("DisplayName").ToString

                    ddl.DataBind()
                Else
                    ddl.Text = ""

                    ddl.ErrorMessage = "Selected Client Not Found !"
                End If

                reader.Close()
            End Using
</code>```

ContentLicense: CC BY-SA 2.5

Body:
clear all items of radcombobox initially and then add a new item manually

this is what i do to set new item when i use web service

     ddl.ClearSelection()
            ddl.Items.Clear()

'below i'm getting the actual value and the text to display
            Using reader As IDataReader = GetClientByClientID(CInt(value))
                If reader.Read Then

'adding the item will show in the dropdown
                    Dim item As New RadComboBoxItem(reader("DisplayName").ToString, reader("ID").ToString)
                    item.Selected = True
                    ddl.Items.Add(item)

'this line will make the combobox text to be displayed correctly
                    ddl.Text = reader("DisplayName").ToString

                    ddl.DataBind()
                Else
                    ddl.Text = ""

                    ddl.ErrorMessage = "Selected Client Not Found !"
                End If

                reader.Close()
            End Using


问:
Is it a good idea to declare static view in android?
The problem :
I have one class and one activity:
The class do the logic and use a complex algorithms that manipulate Textview and ImageView from the activity
What I'm doing :

In activity : static TextView txt1, txt2, txt3, txt4;
so I can use in the class : Activity.txt1

Is it something bad in Android programming ? I wanted to learn best practise. So if you have a better method I would take it. Thanks

答:
Declaring views as static is not suggested for few reasons :

It would lead to memory leak

Static view referenced in one instance won't be available to the other instance

View should only be referenced when the activity is created. Having a static view means we can assign it a reference even before activity is created which leads to problem.

In your case u can return the manipulated text or the new image and display the text or the image from the activity.


问:
Invariant Violation: Element type is invalid: expected a string , or a class/function , but got: undefined
App.js:

```<code>import React from 'react';
import Home from './screens/home';
import Navigator from './routes/drawer';
import Login from './screens/login';

export default class App extends React.Component{

    render() {
        if (false) {
            return (
                <Navigator />
            );
        } else {
            return (
                <Login />
            );
        }
    }
}
</code>```

login.js:

```<code>import React, {View, Text} from 'react';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}
</code>```

This program gives me the error in the title, this DOES work for the Navigator but not for the Login (when the if is set to true instead of false the program runs correctly.) The Navigator acts as a typical drawer container for an android app, but at the bottom of the imports everything appears to act the same as for rendering options. The full error log is below...

```<code>Invariant Violation: Element type is invalid: expected a string (for built in components) or a class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named exports.

Check the render method of 'Login'.

This error is located at:
in Login...
in App...RCTView...AppContainer...
</code>```

答:
Your imports are wrong.

```<code>import React from 'react';
import { View, Text } from 'react-native';
</code>```

There is no export called View or Text inside the react module.

Body:
App.js:

import React from 'react';
import Home from './screens/home';
import Navigator from './routes/drawer';
import Login from './screens/login';

export default class App extends React.Component{

    render() {
        if (false) {
            return (
                <Navigator />
            );
        } else {
            return (
                <Login />
            );
        }
    }
}

login.js:

import React, {View, Text} from 'react';

export default class Login extends React.Component {

    render() {
        return (
            <View style={{ padding: 20 }}>
                <Text>Some text</Text>
            </View>
        )
    }
}

This program gives me the error in the title, this DOES work for the Navigator but not for the Login (when the if is set to true instead of false the program runs correctly.) The Navigator acts as a typical drawer container for an android app, but at the bottom of the imports everything appears to act the same as for rendering options. The full error log is below...

Invariant Violation: Element type is invalid: expected a string (for built in components) or a class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named exports.

Check the render method of 'Login'.

This error is located at:
in Login...
in App...RCTView...AppContainer...

Body:
Your imports are wrong.

import React from 'react';
import { View, Text } from 'react-native';

There is no export called View or Text inside the react module.


问:
Set LC_COLLATE and LC_CTYPE on MacOs
I am trying to create a new database in postgresql with the following script.

```<code>CREATE DATABASE test
OWNER dba
TEMPLATE template0
ENCODING 'UTF-8'
LC_COLLATE 'nb_NO.UTF-8'
LC_CTYPE 'nb_NO.UTF-8'
</code>```

When I run the script I get the following error:

```<code>ERROR:  invalid locale name: "nb_NO.UTF-8"
</code>```

I can see that on Linux Based Systems there is a command called

```<code>locale-gen
</code>```

But I can't find something similar for macOS.

答:
From this ERROR, it is clear that Locale nb_NO.UTF-8 is not present on your MacOS.

And for the command to check the locales on you macOS please use the below command.

```<code>locale -a
</code>```

Title: Set LC_COLLATE and LC_CTYPE on MacOs

Body:
I am trying to create a new database in postgresql with the following script.

CREATE DATABASE test
OWNER dba
TEMPLATE template0
ENCODING 'UTF-8'
LC_COLLATE 'nb_NO.UTF-8'
LC_CTYPE 'nb_NO.UTF-8'

When I run the script I get the following error:

ERROR:  invalid locale name: "nb_NO.UTF-8"

I can see that on Linux Based Systems there is a command called

locale-gen

But I can't find something similar for macOS.

Body:
From this ERROR, it is clear that Locale nb_NO.UTF-8 is not present on your MacOS.

And for the command to check the locales on you macOS please use the below command.

locale -a


问:
PHP:PCRE: How to replace repeatable char
for example I have following string:

```<code>a_b__c___d____e
</code>```

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

```<code>source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e
</code>```

or

```<code>source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f
</code>```

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

答:
this is inline solution :

```<code>preg_replace('/(_{2,})/ie', 'str_repeat("-",strlen("$1"));', $source);
</code>```

and reusable funciton:

```<code>$source = 'a_b__c___d____e_____f';

    function replace_repeatable($source,$char,$replacement,$minrepeat = 2)
    {
          return preg_replace('/(' . preg_quote($char) . '{' . $minrepeat . ',})/ie', 'str_repeat("' . $replacement . '",strlen("$1"));', $source);
    }

    $b = replace_repeatable($source,'_','-',4);
</code>```

Body:
for example I have following string:

a_b__c___d____e

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e

or

source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

Body:
this is inline solution :

preg_replace('/(_{2,})/ie', 'str_repeat("-",strlen("$1"));', $source);

and reusable funciton:

$source = 'a_b__c___d____e_____f';

    function replace_repeatable($source,$char,$replacement,$minrepeat = 2)
    {
          return preg_replace('/(' . preg_quote($char) . '{' . $minrepeat . ',})/ie', 'str_repeat("' . $replacement . '",strlen("$1"));', $source);
    }

    $b = replace_repeatable($source,'_','-',4);


问:
How do you read data from firestore?
I'm trying to learn how to use firestore.

The google documentation says to try this format:

```<code>db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
</code>```

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"

```<code>fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
</code>```

When I try this, I get an error that says querySnapshot is not defined. Screen shot of error message is attached.

I've seen this post and tried its suggestion as follows:

```<code>fsDB.collection("newsletters").query.get().then(function(querySnapshot) {

                            if (querySnapshot.empty) {
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name);
                                    });
                            }

                        });
</code>```

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.

This must have a simple solution, but I can't figure out how to get a record from the database.

NEXT ATTEMPT

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown. These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.

ADD STATE

```<code>class Fndate extends React.Component {
    state = {
        options: [],
        anzic: [],
        country: [],
        region: [],

    }

    selectCountry (val) {
        this.setState({ country: val });
      }

      selectRegion (val) {
        this.setState({ region: val });
      }

    async componentDidMount() {
        // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
        let options = [];
        await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            options.push({
                value: doc.data().title.replace(/( )/g, ''),
                label: doc.data().title + ' - ABS ' + doc.id
            });
            });
        });

        let anzic = [];
        await fsDB.collection("anzic_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            anzic.push({
                value: doc.data().Title.replace(/( )/g, ''),
                label: doc.data().Title + ' - ANZIC ' + doc.id
            });
            });
        });

            await fsDB
            .collection("newsletter")
            .get().then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data().email}`);
                }
            );
            });

        this.setState({
            options,
            anzic
        });
    }
</code>```

5]5

答:
You can use an automated script for this.
All you need is python and firebase_admin.

pip install firebase_admin

download https://github.com/harshit0209/firestore_backup

now run getData.py script.

give it the path of your firebase project private key.

now give the document name.

Title: How do you read data from firestore?

Body:
I'm trying to learn how to use firestore.

The google documentation says to try this format:

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"

fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

When I try this, I get an error that says querySnapshot is not defined. Screen shot of error message is attached.

I've seen this post and tried its suggestion as follows:

fsDB.collection("newsletters").query.get().then(function(querySnapshot) {

                            if (querySnapshot.empty) {
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name);
                                    });
                            }

                        });

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.

This must have a simple solution, but I can't figure out how to get a record from the database.

NEXT ATTEMPT

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown. These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.

ADD STATE

class Fndate extends React.Component {
    state = {
        options: [],
        anzic: [],
        country: [],
        region: [],

    }

    selectCountry (val) {
        this.setState({ country: val });
      }

      selectRegion (val) {
        this.setState({ region: val });
      }

    async componentDidMount() {
        // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
        let options = [];
        await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            options.push({
                value: doc.data().title.replace(/( )/g, ''),
                label: doc.data().title + ' - ABS ' + doc.id
            });
            });
        });

        let anzic = [];
        await fsDB.collection("anzic_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            anzic.push({
                value: doc.data().Title.replace(/( )/g, ''),
                label: doc.data().Title + ' - ANZIC ' + doc.id
            });
            });
        });

            await fsDB
            .collection("newsletter")
            .get().then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data().email}`);
                }
            );
            });

        this.setState({
            options,
            anzic
        });
    }

5]5


问:
CocoaPods spec Validation error
I am creating a private cocoa pod for this below is the pod spec.

My Podspec is

```<code>Pod::Spec.new do |s|
  s.name     = 'RSCrashAdapter'
  s.version  = '1.0.0'
  s.platform = :ios, ‘6.0’
  s.summary  = ‘Crash Reporting Tool’
  s.homepage = 'http://rsjs001:7990/scm/boot/rcrai.git'
  s.author   = { ‘Sushree Swetanka’ => ’s’ushree.swetanka@rishabhsoft.com }
  s.source   = { :git => 'http://rsjs001:7990/scm/boot/rcrai.git', :tag => s.version.to_s }
  s.license      = { :type => 'New BSD License', :file => 'LICENSE' }
  s.source_files = '*.{h,m}'
  s.requires_arc = true
end
</code>```

And I am getting the following error in my terminal: in evey spec it gives me error..

```<code>$ pod spec lint

 -> samplePod.podspec
    - ERROR | [spec] The specification defined in `samplePod.podspec` could not be loaded.

[!] Invalid `samplePod.podspec` file: samplePod.podspec:3: no .<digit> floating literal anymore; put 0 before dot
  spec.version          = ‘1.0.0’
                               ^
samplePod.podspec:3: syntax error, unexpected tFLOAT, expecting '('
  spec.version          = ‘1.0.0’
                                  ^
samplePod.podspec:4: syntax error, unexpected =>, expecting keyword_end
  spec.license          =  :type => 'BSD'
                                   ^
samplePod.podspec:6: syntax error, unexpected =>, expecting keyword_end
  spec.authors          = 'Tony Million' => 'tonymillion@gmail.com'
                                           ^
samplePod.podspec:8: syntax error, unexpected =>, expecting keyword_end
...pec.source           =  :git => 'https://github.com/tonymill...
...                               ^
samplePod.podspec:8: syntax error, unexpected ',', expecting keyword_end
.../tonymillion/Reachability.git', :tag => 'v3.1.0'
...                               ^. Updating CocoaPods might fix the issue.

Analyzed 1 podspec.

[!] The spec did not pass validation.
</code>```

Please help me on solving the spec error....

答:
In my case, I was using the wrong podspec file name.

```<code>pod lib lint WrongPodName.podspec
</code>```

But the right pod name is

```<code>pod lib lint MyPodName.podspec
</code>```

You need to type ls command and check the exact podspec filename.

Title: CocoaPods spec Validation error

Body:
I am creating a private cocoa pod for this below is the pod spec.

My Podspec is

Pod::Spec.new do |s|
  s.name     = 'RSCrashAdapter'
  s.version  = '1.0.0'
  s.platform = :ios, ‘6.0’
  s.summary  = ‘Crash Reporting Tool’
  s.homepage = 'http://rsjs001:7990/scm/boot/rcrai.git'
  s.author   = { ‘Sushree Swetanka’ => ’s’ushree.swetanka@rishabhsoft.com }
  s.source   = { :git => 'http://rsjs001:7990/scm/boot/rcrai.git', :tag => s.version.to_s }
  s.license      = { :type => 'New BSD License', :file => 'LICENSE' }
  s.source_files = '*.{h,m}'
  s.requires_arc = true
end

And I am getting the following error in my terminal: in evey spec it gives me error..

$ pod spec lint

 -> samplePod.podspec
    - ERROR | [spec] The specification defined in `samplePod.podspec` could not be loaded.

[!] Invalid `samplePod.podspec` file: samplePod.podspec:3: no .<digit> floating literal anymore; put 0 before dot
  spec.version          = ‘1.0.0’
                               ^
samplePod.podspec:3: syntax error, unexpected tFLOAT, expecting '('
  spec.version          = ‘1.0.0’
                                  ^
samplePod.podspec:4: syntax error, unexpected =>, expecting keyword_end
  spec.license          =  :type => 'BSD'
                                   ^
samplePod.podspec:6: syntax error, unexpected =>, expecting keyword_end
  spec.authors          = 'Tony Million' => 'tonymillion@gmail.com'
                                           ^
samplePod.podspec:8: syntax error, unexpected =>, expecting keyword_end
...pec.source           =  :git => 'https://github.com/tonymill...
...                               ^
samplePod.podspec:8: syntax error, unexpected ',', expecting keyword_end
.../tonymillion/Reachability.git', :tag => 'v3.1.0'
...                               ^. Updating CocoaPods might fix the issue.

Analyzed 1 podspec.

[!] The spec did not pass validation.

Please help me on solving the spec error....

Body:
In my case, I was using the wrong podspec file name.

pod lib lint WrongPodName.podspec

But the right pod name is

pod lib lint MyPodName.podspec

You need to type ls command and check the exact podspec filename.


问:
C wrapper Python library Json Slicer is slower than pure Python ijson library
According to the official documentation (https://pypi.org/project/jsonslicer/), the basic configuration of Json Slicer yields 586.5K objects/sec,  ijson with Python at the back-end yields 32.2K objects/sec, while ijson with C back-end (ijson.yajl2_cffi) yields 75.7Kobjects/sec.

When I used the two libraries on a deeply nested JSON file of 5GB size, it was expected that Json Slicer, being a wrapper on YAJL (https://lloyd.github.io/yajl/) would execute faster than ijson with pure Python implementation. However, the time taken by Json Slicer was 607.8014905452728 sec, while ijson took 308.19292974472046 sec.

According to various sources (https://lpetr.org/2016/05/30/faster-json-parsing-python-ijson/ , http://explique.me/Ijson/), ijson with C backend should work faster than that with pure Python back-end. However, the time taken by ijson with C backend was 2016.68796280378929 sec.

This behaviour was observed during multiple runs on different occasions on different set of Json files of various sizes.

My system configuration is Intel i7 with 20GB RAM. Multiprocessing was not used during the execution of the script.

Please can somebody explain the root cause of such strange behaviour? Also please let me know a solution to this.

答:
Be aware that since 2.4 ijson has a new yajl2_c backend written all in C (i.e., not using cffi or ctypes), which is ~10x faster than the other ones. And since 2.5 this is the one picked up by default, if present in your installation (probably what happened in your case, hence you saw a faster execution). And since 2.6 there is a new kvitems method that avoid constructing a full object and iterates over its members, which is useful in some situations.

Historically there was no yajl2_c backend, so when people referred to "the C backend" was actually the yajl2_cffi backend. On top of that, people might still be under the impression that ijson defaults to the python backend.

So to answer your question: you are probably running ijson with the yajl2_c backend, and is running faster than JsonSlicer.


问:
Attribute Error during countplot in Python?
I have Pandas DataFrame like this: data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
And I want to make seaborn countplot which will count amount of "good" and "bad", so I have a code:

```<code>ax = sns.countplot(x="Risk", data=data)
ax
</code>```

But when I want to use above code I have error: AttributeError: 'list' object has no attribute 'get'

I want to achieve plot like this:

答:
Check last element in your data. Or, you may have given data=data.Risk as an arguement to countplot(). Otherwise, code is working fine. You need to invoke show()  method using an object of matplotlib.

```<code>>>> import matplotlib.pyplot as plt
>>> import seaborn as sns
>>> data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
>>> ax = sns.countplot(x="Risk", data=data)
>>> plt.show()
</code>```

You had that error because in Data sns.countplot() tries to search data of Risk in Dataset data. It tries following function.

data.get('Risk')
      When you execute above written code, Risk series data will be printed. In your code, data had a list as an input so it generated an error that get is not supported by list. It is used with Pandas DataFrame.
      This image contains count according to the Risk Categories i.e Good and Bad.

Body:
I have Pandas DataFrame like this: data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
And I want to make seaborn countplot which will count amount of "good" and "bad", so I have a code:

ax = sns.countplot(x="Risk", data=data)
ax

But when I want to use above code I have error: AttributeError: 'list' object has no attribute 'get'

I want to achieve plot like this:

Body:
Check last element in your data. Or, you may have given data=data.Risk as an arguement to countplot(). Otherwise, code is working fine. You need to invoke show()  method using an object of matplotlib.

>>> import matplotlib.pyplot as plt
>>> import seaborn as sns
>>> data = pd.DataFrame({"Risk":["good", "good", "bad", "good", "bad", "bad", "good"]})
>>> ax = sns.countplot(x="Risk", data=data)
>>> plt.show()

You had that error because in Data sns.countplot() tries to search data of Risk in Dataset data. It tries following function.

data.get('Risk')
      When you execute above written code, Risk series data will be printed. In your code, data had a list as an input so it generated an error that get is not supported by list. It is used with Pandas DataFrame.
      This image contains count according to the Risk Categories i.e Good and Bad.