问:
how to emulate has_many :through with polymorphic classes
I understand why ActiveRecord can't support has_many :through on polymorphic classes.  But I would like to emulate some of its functionality.  Consider the following, where a join table associates two polymorphic classes:

```<code>class HostPest < ActiveRecord::Base
  belongs_to :host, :polymorphic => true
  belongs_to :pest, :polymorphic => true
end
class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host
end
class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest
end
class Dog < Host ; end
class Cat < Host ; end
class Flea < Pest ; end
class Tick < Pest ; end
</code>```

The goal

Since I can't do has_many :pests, :through=>:host_pests, :as=>:host (etc), I'd like to emulate these four methods:

```<code>dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)
</code>```

Question 1

I've got a working implementation for the first two methods (pests and host), but want to know if this is the best way (specifically, am I overlooking something in ActiveRecord associations that would help):

```<code>class Host < ActiveRecord::Base
  def pests
    HostPest.where(:host_id => self.id, :host_type => self.class).map {|hp| hp.pest}
  end
end
class Pest < ActiveRecord::Base
  def host
    HostPest.where(:pest_id => self.id, :pest_type => self.class).first.host
  end
end
</code>```

Question 2

I'm stumped on how to implement the << and = methods implied here:

```<code>cat.pests << Tick.create  # => HostPest(:host=>cat, :pest=>tick).create
tick.host = Cat.create    # => HostPest(:host=>cat, :pest=>tick).create
</code>```

Any suggestions?  (And again, can ActiveRecord associations provide any help?)

答:
Implementing the host= method on the Pest class is straight forward. We need to make sure we clear the old host while setting a new host (as AR doesn't clear the old value from the intermediary table.).

```<code>class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest

  def host=(host)
    Pest.transaction do
      host_pest.try(:destroy) # destroy the current setting if any
      create_host_pest(:host => host)
    end
  end
end
</code>```

Implementing pests<< method on Host class is bit more involved. Add the pests method on the Host class to return the aggregated list of pests. Add the << method on the object returned by pests method.

```<code>class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host

  # pest list accessor
  def pests
    @pests ||= begin
      host = self # variable to hold the current self.
                  # We need it later in the block
      list = pest_list
      # declare << method on the pests list
      list.singleton_class.send(:define_method, "<<") do |pest|
        # host variable accessible in the block
        host.host_pests.create(:pest => pest)
      end
      list
    end
  end

private
  def pest_list
    # put your pest concatenation code here
  end
end
</code>```

Now

```<code>cat.pests # returns a list
cat.pests << flea # appends the flea to the pest list
</code>```

Body:
I understand why ActiveRecord can't support has_many :through on polymorphic classes.  But I would like to emulate some of its functionality.  Consider the following, where a join table associates two polymorphic classes:

class HostPest < ActiveRecord::Base
  belongs_to :host, :polymorphic => true
  belongs_to :pest, :polymorphic => true
end
class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host
end
class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest
end
class Dog < Host ; end
class Cat < Host ; end
class Flea < Pest ; end
class Tick < Pest ; end

The goal

Since I can't do has_many :pests, :through=>:host_pests, :as=>:host (etc), I'd like to emulate these four methods:

dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)

Question 1

I've got a working implementation for the first two methods (pests and host), but want to know if this is the best way (specifically, am I overlooking something in ActiveRecord associations that would help):

class Host < ActiveRecord::Base
  def pests
    HostPest.where(:host_id => self.id, :host_type => self.class).map {|hp| hp.pest}
  end
end
class Pest < ActiveRecord::Base
  def host
    HostPest.where(:pest_id => self.id, :pest_type => self.class).first.host
  end
end

Question 2

I'm stumped on how to implement the << and = methods implied here:

cat.pests << Tick.create  # => HostPest(:host=>cat, :pest=>tick).create
tick.host = Cat.create    # => HostPest(:host=>cat, :pest=>tick).create

Any suggestions?  (And again, can ActiveRecord associations provide any help?)

Body:
Implementing the host= method on the Pest class is straight forward. We need to make sure we clear the old host while setting a new host (as AR doesn't clear the old value from the intermediary table.).

class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest

  def host=(host)
    Pest.transaction do
      host_pest.try(:destroy) # destroy the current setting if any
      create_host_pest(:host => host)
    end
  end
end

Implementing pests<< method on Host class is bit more involved. Add the pests method on the Host class to return the aggregated list of pests. Add the << method on the object returned by pests method.

class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host

  # pest list accessor
  def pests
    @pests ||= begin
      host = self # variable to hold the current self.
                  # We need it later in the block
      list = pest_list
      # declare << method on the pests list
      list.singleton_class.send(:define_method, "<<") do |pest|
        # host variable accessible in the block
        host.host_pests.create(:pest => pest)
      end
      list
    end
  end

private
  def pest_list
    # put your pest concatenation code here
  end
end

Now

cat.pests # returns a list
cat.pests << flea # appends the flea to the pest list


来源: stackexchange

问:
Implementing linked list
I am creating a linked list but after printing it I am only getting the last element in an unending loop here is the code
I guess there is some error in creating the Linked list how to solve it

Link to my code my linked List

#include<iostream>

using namespace std;

struct node{
    int data;    // for data component
    node* next;  // to hold addr of next
}*head_first=NULL;

void create(int* a, int n) // a is array and n is sizeof
{
    node *newnode,*temp;

    newnode=new node();

    for(int i=0;i<n;i++){
        newnode->data=a[i];
        newnode->next=NULL;

        if(head_first==NULL){
           temp=head_first=newnode;
           cout<<"head assigned"<<endl;
        }
        else{
            temp->next=newnode;
            temp=newnode;
            cout<<i<<" node created"<<endl;
        }
    }
}

void dis(node *p){
    while(p!=NULL){
        cout<
data <<endl;
        p=p->next;
    }
}

int main(){

    int a[]={10,20,30,40,50,60};
    int size=sizeof(a)/sizeof(int);
    create(a,size);
   dis(head_first);
    return 0;
}
```

答:
Aside of the raw pointer and nullptr issue, I noticed that your node points itself. I think the code have to be modified like this:</p>
```<code>void create(int* a, int n) // a is array and n is sizeof
{
    node *newnode,*temp;

    for(int i=0;i<n;i++){
        newnode=new node();
        newnode->data=a[i];
        newnode->next=NULL;

        if(head_first==NULL){
           temp=head_first=newnode;
           cout<<"head assigned"<<endl;
        }
        else{
            temp->next=newnode;
            temp=newnode;
            cout<<i<<" node created"<<endl;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Implementing linked list

Body:
Aside of the raw pointer and nullptr issue, I noticed that your node points itself. I think the code have to be modified like this:

void create(int* a, int n) // a is array and n is sizeof
{
    node *newnode,*temp;

    for(int i=0;i<n;i++){
        newnode=new node();
        newnode->data=a[i];
        newnode->next=NULL;

        if(head_first==NULL){
           temp=head_first=newnode;
           cout<<"head assigned"<<endl;
        }
        else{
            temp->next=newnode;
            temp=newnode;
            cout<<i<<" node created"<<endl;
        }
    }
}


问:
How to make SF Symbols in SwiftUI have the same width
Is there a way to make all symbols in the same size have the same width?

As you can see from the screenshot below, person.2.fill has the longest width and square.and.arrow.up is the nearest. Setting the font to a mono-spaced font does not seem to change anything in this case.

```<code>Image(systemName: "square.and.arrow.up")
    .font(Font.system(size: 18, weight: .medium, design: .monospaced))
</code>```

A workaround would be not "forcing" them to have the same width but horizontally centered inside the same width container.

答:
I fixed this using PreferenceKey, also work well with dynamic font sizing.

Test in Xcode13.2 Swift5.5

```<code>struct ContentView: View {

    @State private var iconWidth: Double = 0

    private var icons: [String] = ["person.crop.circle", "tag", "text.book.closed", "icloud.and.arrow.up"]

    var body: some View {
        List(icons, id: \.self) { iconName in
            HStack {
                Image(systemName: iconName)
                    .sync(with: $iconWidth)
                    .frame(width: iconWidth)

                Text(iconName)
            }
            .onPreferenceChange(SymbolWidthPreferenceKey.self) { iconWidth = $0 }
        }
    }
}

struct SymbolWidthPreferenceKey: PreferenceKey {

    static var defaultValue: Double = 0

    static func reduce(value: inout Double, nextValue: () -> Double) {
        value = max(value, nextValue())
    }
}

struct SymbolWidthModifier: ViewModifier {

    @Binding var width: Double

    func body(content: Content) -> some View {
        content
            .background(GeometryReader { geo in
                Color
                    .clear
                    .preference(key: SymbolWidthPreferenceKey.self, value: geo.size.width)
            })
    }
}

extension Image {

    func sync(with width: Binding<Double>) -> some View {
         modifier(SymbolWidthModifier(width: width))
    }
}
</code>```

Body:
Is there a way to make all symbols in the same size have the same width?

As you can see from the screenshot below, person.2.fill has the longest width and square.and.arrow.up is the nearest. Setting the font to a mono-spaced font does not seem to change anything in this case.

Image(systemName: "square.and.arrow.up")
    .font(Font.system(size: 18, weight: .medium, design: .monospaced))

A workaround would be not "forcing" them to have the same width but horizontally centered inside the same width container.

Body:
I fixed this using PreferenceKey, also work well with dynamic font sizing.

Test in Xcode13.2 Swift5.5

struct ContentView: View {

    @State private var iconWidth: Double = 0

    private var icons: [String] = ["person.crop.circle", "tag", "text.book.closed", "icloud.and.arrow.up"]

    var body: some View {
        List(icons, id: \.self) { iconName in
            HStack {
                Image(systemName: iconName)
                    .sync(with: $iconWidth)
                    .frame(width: iconWidth)

                Text(iconName)
            }
            .onPreferenceChange(SymbolWidthPreferenceKey.self) { iconWidth = $0 }
        }
    }
}

struct SymbolWidthPreferenceKey: PreferenceKey {

    static var defaultValue: Double = 0

    static func reduce(value: inout Double, nextValue: () -> Double) {
        value = max(value, nextValue())
    }
}

struct SymbolWidthModifier: ViewModifier {

    @Binding var width: Double

    func body(content: Content) -> some View {
        content
            .background(GeometryReader { geo in
                Color
                    .clear
                    .preference(key: SymbolWidthPreferenceKey.self, value: geo.size.width)
            })
    }
}

extension Image {

    func sync(with width: Binding<Double>) -> some View {
         modifier(SymbolWidthModifier(width: width))
    }
}


问:
using jansson api's create json file write data into file but i need new line for very key
Output:

```<code>{"PSM": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 1, "Pvid": 106}, "SYSCFG": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 107}, "rbus_event": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 108}, "SYSEVENT": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 109}}
</code>```

Expected Output:

```<code>{"PSM": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 1,
 "Pvid": 106},
"SYSCFG": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 107},
 "rbus_event": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 108},
 "SYSEVENT": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 109}}
</code>```

答:
You get a prettified output of your JSON when encoding with a proper indentation.

If you read a JSON which is not already prettified you have to decode it first and encode it the way you want - something like:

```<code>json_t *root = json_loads(input, 0, &error);

if (root) {
    char *dump = json_dumps(root, JSON_INDENT(4));

    if (dump) {
        printf("%s", dump);
        free(dump);
        dump = NULL;
    }
}

</code>```

Body:
Output:

{"PSM": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 1, "Pvid": 106}, "SYSCFG": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 107}, "rbus_event": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 108}, "SYSEVENT": {"LinkName": "ath6", "LinkType": "WiFi", "PriorityTag": 0, "Pvid": 109}}

Expected Output:

{"PSM": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 1,
 "Pvid": 106},
"SYSCFG": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 107},
 "rbus_event": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 108},
 "SYSEVENT": {
"LinkName": "ath6",
 "LinkType": "WiFi",
 "PriorityTag": 0,
 "Pvid": 109}}

Body:
You get a prettified output of your JSON when encoding with a proper indentation.

If you read a JSON which is not already prettified you have to decode it first and encode it the way you want - something like:

json_t *root = json_loads(input, 0, &error);

if (root) {
    char *dump = json_dumps(root, JSON_INDENT(4));

    if (dump) {
        printf("%s", dump);
        free(dump);
        dump = NULL;
    }
}


问:
MySQL query for current GMT time
This sounds simple enough but I haven't been able to figure out how to use a simple SELECT statement to return the current time in GMT.

I have been trying to use CONVERT_TZ() to convert NOW() to GMT based on the server time zone and the GMT time zone but for some reason it returns NULL when I put in the text time zones. The only way I get a result is to actually put in the offsets which is getting way too complicated for what should be a really simple operation. Here is what I mean:

```<code>mysql> SELECT CONVERT_TZ(NOW(),@@global.system_time_zone,'GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'PST','GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'-08:00','+00:00');
2010-02-13 18:28:22
</code>```

All I need is a simple query to return the current time in GMT. Thanks in advance for your help!

答:
NO BUG in CONVERT_TZ()

To use CONVERT_TZ() you need to install the time-zone tables otherwise MySql returns NULL.

From the CLI run the following as root

# mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql

SEE http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

Thanks

http://www.ArcanaVision.com (SJP 2011-08-18)

ContentLicense: CC BY-SA 2.5

Title: MySQL query for current GMT time

Body:
This sounds simple enough but I haven't been able to figure out how to use a simple SELECT statement to return the current time in GMT.

I have been trying to use CONVERT_TZ() to convert NOW() to GMT based on the server time zone and the GMT time zone but for some reason it returns NULL when I put in the text time zones. The only way I get a result is to actually put in the offsets which is getting way too complicated for what should be a really simple operation. Here is what I mean:

mysql> SELECT CONVERT_TZ(NOW(),@@global.system_time_zone,'GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'PST','GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'-08:00','+00:00');
2010-02-13 18:28:22

All I need is a simple query to return the current time in GMT. Thanks in advance for your help!

ContentLicense: CC BY-SA 3.0


问:
Why codecvt can't convert unicode outside BMP to u16string?
I am trying to understand C++ unicode and having this confused me now.

Code:

```<code>#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;

void trial1(){
    string a = "\U00010000z";
    cout << a << endl;
    u16string b;
    std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
    b = converter.from_bytes(a);
    u16string c = b.substr(0, 1);
    string q = converter.to_bytes(c);
    cout << q << endl;
}

void trial2(){
    u16string a = u"\U00010000";
    cout << a.length() << endl; // 2
    std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
    string b = converter.to_bytes(a);
}

int main() {
//    both don't work
//    trial1();
//    trial2();
    return 0;
}
</code>```

I have tested that u16string can store unicode outside BMP as surrogate pairs, e.g. u"\U00010000" is stored with 2 char16_t.

So why std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter; doesn't work for both trial1 and trial2 and throw an exception?

答: std::codecvt_utf8 does not support conversions to/from UTF-16, only UCS-2 and UTF-32.  You need to use std::codecvt_utf8_utf16 instead.

Body:
I am trying to understand C++ unicode and having this confused me now.

Code:

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;

void trial1(){
    string a = "\U00010000z";
    cout << a << endl;
    u16string b;
    std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
    b = converter.from_bytes(a);
    u16string c = b.substr(0, 1);
    string q = converter.to_bytes(c);
    cout << q << endl;
}

void trial2(){
    u16string a = u"\U00010000";
    cout << a.length() << endl; // 2
    std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter;
    string b = converter.to_bytes(a);
}

int main() {
//    both don't work
//    trial1();
//    trial2();
    return 0;
}

I have tested that u16string can store unicode outside BMP as surrogate pairs, e.g. u"\U00010000" is stored with 2 char16_t.

So why std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter; doesn't work for both trial1 and trial2 and throw an exception?


问:
Send graph as email body using powershell
I am having below code to create graph using powerhsell Import-Excel

```<code>$outputXLSX = "C:\report_10_02.xlsx"
$data = Import-Excel -Path $outputXLSX

$cd = New-ExcelChartDefinition -XRange Name -YRange Count -ChartType ColumnStacked3D -Height 300 -Title "Latency Count" -Width 1000 -SeriesHeader Count
$data | Export-Excel $outputXLSX -ExcelChartDefinition $cd -AutoNameRange #-WorksheetName "Sheet2"
</code>```

I need excel file as mail attachment and graph as email body.

Please let me know how to do this.

答:
I have answered an question to mails from PowerShell before and this should help you:

```<code>$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "xyz@outlook.com"
$Mail.Subject = "Your Subject"
$Mail.Body = "Your Text"
$mail.attachments.add("C:\Users\YourUser\Documents\test.txt") #path to file
$Mail.Send()
</code>```

If it works with Export-Excel is something I do not know, but you can easily try it out by using:

```<code>$mail.attachments.add(Export-Excel)
</code>```

Body:
I am having below code to create graph using powerhsell Import-Excel

$outputXLSX = "C:\report_10_02.xlsx"
$data = Import-Excel -Path $outputXLSX

$cd = New-ExcelChartDefinition -XRange Name -YRange Count -ChartType ColumnStacked3D -Height 300 -Title "Latency Count" -Width 1000 -SeriesHeader Count
$data | Export-Excel $outputXLSX -ExcelChartDefinition $cd -AutoNameRange #-WorksheetName "Sheet2"

I need excel file as mail attachment and graph as email body.

Please let me know how to do this.

Body:
I have answered an question to mails from PowerShell before and this should help you:

$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "xyz@outlook.com"
$Mail.Subject = "Your Subject"
$Mail.Body = "Your Text"
$mail.attachments.add("C:\Users\YourUser\Documents\test.txt") #path to file
$Mail.Send()

If it works with Export-Excel is something I do not know, but you can easily try it out by using:

$mail.attachments.add(Export-Excel)


问:
How to merge two sql queries and get output?
I am extending the How to use Inner Joins with where clause? question because I need some extrnsion of this query results.

Here I have made a php script as below. This because a one table is in another server and it is not in same localhost. So I have created two different sql queries

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project1";

$servername2 = "112.76.456.89";
$username2 = "user";
$password2 = "user990";
$dbname2= "project2";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Create connection
$conn2 = mysqli_connect($servername2, $username2, $password2, $dbname2);
// Check connection
if (!$conn2) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql1 = "SELECT t2.UserID,
t1.Username,
t2.TotalAmountResetDate,
t2.TotalAmount,
sum(COALESCE(Totalnvested,0)) Totalnvested
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username AND
investment.total_invested_date BETWEEN '2022-01-31' and '2022-02-12'
WHERE t2.TotalAmountResetDate='2022-01-31' ";

$sql2="SELECT Username,sum(TotalExpenses) from TotalExpensesTable where date_of_expense_date between '2022-01-31' and '2022-02-12'
group by Username";

$result1 = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn2, $sql2);

mysqli_close($conn);
mysqli_close($conn2);
?>
</code>```

From each sql query I can get the output as below.

Query1;

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested
1        John              1/31/2022               -12       45000
2        Micheal           1/31/2022               345       45000
3        Ann               1/31/2022               213       45000
4        Shasha            1/31/2022               0         0
5        mike              1/31/2022               0         0
</code>```

Query2:

```<code>Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
</code>```

Now I need to get the output by combining these two as below,

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0
</code>```

Can someone show me how should I get this kind of output using merging of above two queries? Do I need to use foreach loop?

I need to get UserId,Username,TotalAmountResetDate,TotalAmount,Totalnvested,TotalExpenses,TotalBalance then I can show it using a HTML table.

答:
An example using hashMap to merge two datasets.

<?php

$result1 = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn2, $sql2);

$res1 = mysqli_fetch_all($result1, MYSQLI_ASSOC);
$res2 = mysqli_fetch_all($result2, MYSQLI_ASSOC);

$hashMapRes2 = array_reduce($res2, function ($carry, $item) {
    $username = $item['Username'];
    if (!isset($carry[$username])) {
        $carry[$username] = $item;
    }
    return $carry;
}, []);

$output = array_map(function ($item) use ($hashMapRes2) {
    $username = $item['Username'];
    if (isset($hashMapRes2[$username])) {
        $item['TotalExpenses'] = $hashMapRes2[$username]['TotalExpenses'];
    } else {
        $item['TotalExpenses'] = 0;
    }
    return $item;
}, $res1);

print_r($output);
```
<p>Sandbox Here</p>
<p>Output:</p>
```Array
(
    [0] => Array
        (
            [UserId] => 1
            [Username] => John
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => -12
            [Totalnvested] => 3055
            [TotalExpenses] => 11
        )

    [1] => Array
        (
            [UserId] => 1
            [Username] => Micheal
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => 50
            [Totalnvested] => 3055
            [TotalExpenses] => 12
        )

    [2] => Array
        (
            [UserId] => 1
            [Username] => Shasha
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => -12
            [Totalnvested] => 3055
            [TotalExpenses] => 0
        )

)
```

Body:
I am extending the How to use Inner Joins with where clause? question because I need some extrnsion of this query results.

Here I have made a php script as below. This because a one table is in another server and it is not in same localhost. So I have created two different sql queries

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project1";

$servername2 = "112.76.456.89";
$username2 = "user";
$password2 = "user990";
$dbname2= "project2";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Create connection
$conn2 = mysqli_connect($servername2, $username2, $password2, $dbname2);
// Check connection
if (!$conn2) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql1 = "SELECT t2.UserID,
t1.Username,
t2.TotalAmountResetDate,
t2.TotalAmount,
sum(COALESCE(Totalnvested,0)) Totalnvested
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username AND
investment.total_invested_date BETWEEN '2022-01-31' and '2022-02-12'
WHERE t2.TotalAmountResetDate='2022-01-31' ";

$sql2="SELECT Username,sum(TotalExpenses) from TotalExpensesTable where date_of_expense_date between '2022-01-31' and '2022-02-12'
group by Username";

$result1 = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn2, $sql2);

mysqli_close($conn);
mysqli_close($conn2);
?>

From each sql query I can get the output as below.

Query1;

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested
1        John              1/31/2022               -12       45000
2        Micheal           1/31/2022               345       45000
3        Ann               1/31/2022               213       45000
4        Shasha            1/31/2022               0         0
5        mike              1/31/2022               0         0

Query2:

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Now I need to get the output by combining these two as below,

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

Can someone show me how should I get this kind of output using merging of above two queries? Do I need to use foreach loop?

I need to get UserId,Username,TotalAmountResetDate,TotalAmount,Totalnvested,TotalExpenses,TotalBalance then I can show it using a HTML table.

Body:
An example using hashMap to merge two datasets.

<?php

$result1 = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn2, $sql2);

$res1 = mysqli_fetch_all($result1, MYSQLI_ASSOC);
$res2 = mysqli_fetch_all($result2, MYSQLI_ASSOC);

$hashMapRes2 = array_reduce($res2, function ($carry, $item) {
    $username = $item['Username'];
    if (!isset($carry[$username])) {
        $carry[$username] = $item;
    }
    return $carry;
}, []);

$output = array_map(function ($item) use ($hashMapRes2) {
    $username = $item['Username'];
    if (isset($hashMapRes2[$username])) {
        $item['TotalExpenses'] = $hashMapRes2[$username]['TotalExpenses'];
    } else {
        $item['TotalExpenses'] = 0;
    }
    return $item;
}, $res1);

print_r($output);

Sandbox Here

Output:

Array
(
    [0] => Array
        (
            [UserId] => 1
            [Username] => John
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => -12
            [Totalnvested] => 3055
            [TotalExpenses] => 11
        )

    [1] => Array
        (
            [UserId] => 1
            [Username] => Micheal
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => 50
            [Totalnvested] => 3055
            [TotalExpenses] => 12
        )

    [2] => Array
        (
            [UserId] => 1
            [Username] => Shasha
            [TotalAmountResetDate ] => 1/31/2022
            [TotalAmount] => -12
            [Totalnvested] => 3055
            [TotalExpenses] => 0
        )

)


问:
Test if an internet connection is present in python
I have the following code that checks if an internet connection is present.

```<code>import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False
</code>```

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

答:
This is how we do it in our production:

```<code>import socket, sys

def ValidateConnection(host: str):
    try:
        DnsLookup: tuple = socket.gethostbyname_ex(host.strip())
        if DnsLookup[-1]:
            ipaddress: str = DnsLookup[-1][0]
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                sock.settimeout(1.0)
                result: int = sock.connect_ex((ipaddress,53))
                if result == 0:
                    return(True)
    except Exception as e:
        if "[Errno 11001] getaddrinfo failed" in str(e):
            print("Unable to lookup host: "+host)
        else:
            print("Unexpected error: "+str(e), sys.exc_info()[0])
    return(False)
</code>```

Results:

```<code>print(ValidateConnection("this.does.not.exist"))
Unable to lookup host: this.does.not.exist
False

print(ValidateConnection("one.one.one.one"))
True
</code>```

Python 3.9.9

Body:
I have the following code that checks if an internet connection is present.

import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

Body:
This is how we do it in our production:

import socket, sys

def ValidateConnection(host: str):
    try:
        DnsLookup: tuple = socket.gethostbyname_ex(host.strip())
        if DnsLookup[-1]:
            ipaddress: str = DnsLookup[-1][0]
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                sock.settimeout(1.0)
                result: int = sock.connect_ex((ipaddress,53))
                if result == 0:
                    return(True)
    except Exception as e:
        if "[Errno 11001] getaddrinfo failed" in str(e):
            print("Unable to lookup host: "+host)
        else:
            print("Unexpected error: "+str(e), sys.exc_info()[0])
    return(False)

Results:

print(ValidateConnection("this.does.not.exist"))
Unable to lookup host: this.does.not.exist
False

print(ValidateConnection("one.one.one.one"))
True

Python 3.9.9


问:
Use Class Extension for Selective Visibility in Objective-C
Would it make any sense to put class extensions in their own .h files and #import them selectively to get various levels of visibility for a class' methods and properties? If this is a bad idea (or would not work), why?

答: Class extension (as opposed to subclassing) in Objective-C is accomplished with Categories. In Xcode, go to File > New > File and select Objective-C Category. It will ask you what to call the category and what class it should extend. You'll get a .h/.m pair in which to put your interface and implementation, respectively. If you want access to the features provided in your extension, just import its .h file.</p>


问:
How to elegantly PATCH changes into mongodb without path conflicts
So I'm attempting to do a PATCH request to a MongoDB store, by updating an element in an sub-array. This is what the data looks like:

const booksSchema = mongoose.Schema(
  {
    name: { type: String, trim: true },
    author: { type: String, trim: true },
  },
  { timestamps: true },
)
const Book = mongoose.model('Book', bookSchema)

const librarySchema = mongoose.Schema(
  { books: [ Books.schema ] },
  { timestamps: true },
)
const Library = mongoose.model('Library', librarySchema)
```
<p>And this is how I'm updating the data:</p>
<pre class="lang-js prettyprint-override"><code>  const library = await Library.findOneAndUpdate(
    { _id: libraryId, "books._id": bookId },
    { $set: { "books.$": bookBody } },
  )
</code>```

And in the process, I've run into problems with the automated timestamp update conflicting with the $set command:

Updating the path 'books.$.updatedAt' would create a conflict at 'books.$'
```
<p>The best solution I've come across to make this type of update without removing the automated timestamp update is to manually set each field, like this:</p>
<pre class="lang-js prettyprint-override"><code>  const library = await Library.findOneAndUpdate(
    { _id: libraryId, "book._id": bookId },
    {
      $set: {
        "book.$.name": bookBody.name,
        "book.$.author": bookBody.author,
      }
    },
  )
</code>```

...but this solution is very verbosely.

Is there a more elegant way to do this type of PATCH request, perhaps using some kinda of object destructuring, that doesn't require maintaining a mapping of each field?

答:
In fact, if your intention is to perform a PATCH operation the way it's described in HTTP protocol:

The HTTP PATCH request method applies partial modifications to a
resource.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH

You should go with the "verbose" solution in your case, because your alternative update { $set: { "books.$": bookBody } } will delete any property missing in the update from the updated book. It's not how PATCH should work, it's how PUT is intended to work.

You can make your code a little less verbose by introducing a helper function performing something like this (example uses lodash):

import _ from 'lodash'

_.mapValues(book, (value) => {
   _.mapKeys(value, (innerValue, innerKey) => (
     `book.$.${innerKey}`
   )
)
```

Body:
So I'm attempting to do a PATCH request to a MongoDB store, by updating an element in an sub-array. This is what the data looks like:

const booksSchema = mongoose.Schema(
  {
    name: { type: String, trim: true },
    author: { type: String, trim: true },
  },
  { timestamps: true },
)
const Book = mongoose.model('Book', bookSchema)

const librarySchema = mongoose.Schema(
  { books: [ Books.schema ] },
  { timestamps: true },
)
const Library = mongoose.model('Library', librarySchema)

And this is how I'm updating the data:

  const library = await Library.findOneAndUpdate(
    { _id: libraryId, "books._id": bookId },
    { $set: { "books.$": bookBody } },
  )

And in the process, I've run into problems with the automated timestamp update conflicting with the $set command:

Updating the path 'books.$.updatedAt' would create a conflict at 'books.$'

The best solution I've come across to make this type of update without removing the automated timestamp update is to manually set each field, like this:

  const library = await Library.findOneAndUpdate(
    { _id: libraryId, "book._id": bookId },
    {
      $set: {
        "book.$.name": bookBody.name,
        "book.$.author": bookBody.author,
      }
    },
  )

...but this solution is very verbosely.

Is there a more elegant way to do this type of PATCH request, perhaps using some kinda of object destructuring, that doesn't require maintaining a mapping of each field?


问:
Does openGauss have the full support of GNU Readline?
Does openGauss have the full support of GNU Readline?

Readline library should allow gsql to remember what command I've entered even from last session. However, when I started a new session, and then I pressed the up arrow, nothing happened.

答:
openGauss support readline. You can use it by doing:

Compile configure with --with-readline option;

Using gsql with -r option.


问:
Using Hibernate for enumerations / type codes
I am trying to setup the Hibernate XML files such that enumerations are accessed as string values rather than class instances.

The DB schema:

```<code>table MyEntity (EntityId, EnumerationId)
table MyEnumeration (EnumerationId, EnumerationValue)
</code>```

This provides a mapping of many MyEntity rows to one MyEnumeration row. An example of MyEnumeration could be countries.

Hibernate hbm2hbmxml produces:

```<code><hibernate-mapping>
    <class name="MyEntity" table="MyEntity">
        <many-to-one name="myEnumeration" class="MyEnumeration" fetch="select">
            <column name="EnumerationId" length="36" />
        </many-to-one>
        ...
</hibernate-mapping>
</code>```

The mapping above works in that I can now access MyEnumeration instances in my code and then get the EnumerationValue. However, I would like to abstract that. Instead, I would like to access the myEnumeration property as a string instead of a MyEnumeration class.

How can I do this with the Hibernate mapping file?

答:
```<code>@Transient
public String getMyEnumerationValue() {
    if (this.myEnumeration == null) {
        return null;
    }
    else {
        return this.myEnumeration.getValue();
    }
}
</code>```

A setter is more complicated, because it would need access to the session to get the ID of the enumeration having the given value (provided it's unique) in order to populate the myEnumeration field.

Body:
I am trying to setup the Hibernate XML files such that enumerations are accessed as string values rather than class instances.

The DB schema:

table MyEntity (EntityId, EnumerationId)
table MyEnumeration (EnumerationId, EnumerationValue)

This provides a mapping of many MyEntity rows to one MyEnumeration row. An example of MyEnumeration could be countries.

Hibernate hbm2hbmxml produces:

<hibernate-mapping>
    <class name="MyEntity" table="MyEntity">
        <many-to-one name="myEnumeration" class="MyEnumeration" fetch="select">
            <column name="EnumerationId" length="36" />
        </many-to-one>
        ...
</hibernate-mapping>

The mapping above works in that I can now access MyEnumeration instances in my code and then get the EnumerationValue. However, I would like to abstract that. Instead, I would like to access the myEnumeration property as a string instead of a MyEnumeration class.

How can I do this with the Hibernate mapping file?

Body:
@Transient
public String getMyEnumerationValue() {
    if (this.myEnumeration == null) {
        return null;
    }
    else {
        return this.myEnumeration.getValue();
    }
}

A setter is more complicated, because it would need access to the session to get the ID of the enumeration having the given value (provided it's unique) in order to populate the myEnumeration field.


问:
TypeError: Error Cannot read property '0' of undefined when returning a response from chatbot
I'm currently working on an API for my chatbot that saves user input to my database. It works fine when I do queries and it saves to my database without any problems. My problem is that it should send a response that it got the user query.

Here's my code for the route/controller:

```<code>if (req.body.queryResult.parameters.informationType == "appointment") {
    const user = {
        firstName: req.body.queryResult.parameters.firstName,
        lastName: req.body.queryResult.parameters.lastName,
        mobile: req.body.queryResult.parameters.mobile,
        email: req.body.queryResult.parameters.email,
        status: "Pending",
        informationType: req.body.queryResult.parameters.informationType,
        appointmentDate: dateToISO(req.body.queryResult.parameters.appointmentDate),
        };

        db.db()
        .collection("users")
        .insertOne(user, (err, result) => {
            if (err) {
                return res.json({
                    "fulfillmentText": "Error has occured. Cannot add user.",
                 });
            } else {
                var firstName = result.ops[0].firstName;
                var lastName = result.ops[0].lastName;

                return res.json({
                    "fulfillmentText":
                            "Okay, got it " +
                            firstName +
                            " " +
                            lastName +
                            ". We will send an email or text message from the contact info you have provided once your appointment has been approved.",
                });
            }
        })
}
</code>```

Also, here's its model:

```<code>var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var user = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  mobile: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    required: true,
  },
  appointmentDate: {
    type: Date,
    required: true,
  },
  informationType: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("users", user);

</code>```

答:
Okay, I stumbled upon this post and read some documentation. Apparently, the approach that I used doesn't work anymore.

After hours of trying and scouring various post, I finally found the solution (which was actually a no-brainer). This is what I did:

```<code>var firstName = req.body.queryResult.parameters.firstName;
var lastName = req.body.queryResult.parameters.lastName;
</code>```

Body:
I'm currently working on an API for my chatbot that saves user input to my database. It works fine when I do queries and it saves to my database without any problems. My problem is that it should send a response that it got the user query.

Here's my code for the route/controller:

if (req.body.queryResult.parameters.informationType == "appointment") {
    const user = {
        firstName: req.body.queryResult.parameters.firstName,
        lastName: req.body.queryResult.parameters.lastName,
        mobile: req.body.queryResult.parameters.mobile,
        email: req.body.queryResult.parameters.email,
        status: "Pending",
        informationType: req.body.queryResult.parameters.informationType,
        appointmentDate: dateToISO(req.body.queryResult.parameters.appointmentDate),
        };

        db.db()
        .collection("users")
        .insertOne(user, (err, result) => {
            if (err) {
                return res.json({
                    "fulfillmentText": "Error has occured. Cannot add user.",
                 });
            } else {
                var firstName = result.ops[0].firstName;
                var lastName = result.ops[0].lastName;

                return res.json({
                    "fulfillmentText":
                            "Okay, got it " +
                            firstName +
                            " " +
                            lastName +
                            ". We will send an email or text message from the contact info you have provided once your appointment has been approved.",
                });
            }
        })
}

Also, here's its model:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var user = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  mobile: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    required: true,
  },
  appointmentDate: {
    type: Date,
    required: true,
  },
  informationType: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("users", user);

Body:
Okay, I stumbled upon this post and read some documentation. Apparently, the approach that I used doesn't work anymore.

After hours of trying and scouring various post, I finally found the solution (which was actually a no-brainer). This is what I did:

var firstName = req.body.queryResult.parameters.firstName;
var lastName = req.body.queryResult.parameters.lastName;


问:
How to ensure 2 injected interfaces are instantiated as the same object instance
Given the following classes

```<code>public class RWRepository<TEntity, TEntityId> : IRWRepository<TEntity, TEntityId>
</code>```

and

```<code>internal sealed class EagerLoadingRWRepository<TEntity>
    : RWRepository<TEntity, Guid>
    , IEagerLoadingRWRepository<TEntity>
</code>```

I am registering these in my DI container like this (where service is IServiceCollection)

```<code>services.AddScoped(typeof(IRWRepository<,>), typeof(RWRepository<,>));
services.AddScoped(typeof(IEagerLoadingRWRepository<>), typeof(EagerLoadingRWRepository<>));
</code>```

Say I inject both of these into 2 different handlers, both within the same scope. How I can ensure that both handlers will use the same object instance for each injected interface?

I.e. if both interfaces are injected, then both should use the same instance of EagerLoadingRWRepository, which inherits from RWRepository

答:
This will be very cumbersome to do with MS.DI (ASP.NET Core's built-in DI Container), because it requires you to make each closed registration explicitly.

For instance:

services.AddScoped<IEagerLoadingRWRepository<Person>, EagerLoadingRWRepository<Person>>();
services.AddScoped<IRWRepository<Person, Guid>>(
    c => (IRWRepository<Person, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Person>>());

services.AddScoped<IEagerLoadingRWRepository<Order>, EagerLoadingRWRepository<Order>>();
services.AddScoped<IRWRepository<Order, Guid>>(
    c => (IRWRepository<Order, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Order>>());

services.AddScoped<IEagerLoadingRWRepository<Shipment>, EagerLoadingRWRepository<Shipment>>();
services.AddScoped<IRWRepository<Shipment, Guid>>(
    c => (IRWRepository<Shipment, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Shipment>>());
```

Body:
Given the following classes

public class RWRepository<TEntity, TEntityId> : IRWRepository<TEntity, TEntityId>

and

internal sealed class EagerLoadingRWRepository<TEntity>
    : RWRepository<TEntity, Guid>
    , IEagerLoadingRWRepository<TEntity>

I am registering these in my DI container like this (where service is IServiceCollection)

services.AddScoped(typeof(IRWRepository<,>), typeof(RWRepository<,>));
services.AddScoped(typeof(IEagerLoadingRWRepository<>), typeof(EagerLoadingRWRepository<>));

Say I inject both of these into 2 different handlers, both within the same scope. How I can ensure that both handlers will use the same object instance for each injected interface?

I.e. if both interfaces are injected, then both should use the same instance of EagerLoadingRWRepository, which inherits from RWRepository


问:
Using a DataTrigger to set the properties of a ScaleTransform
A failed XAML attempt here - I'm obviously doing something stupid with the Style/Setter syntax. I just want to flip an element based on some bindings by setting the ScaleX and ScaleY properties of a ScaleTransform from a DataTrigger. Setter.Property obviously doesn't support a property path, but how can I get round this? I can't set the whole RenderTransform property because ScaleX and ScaleY are independent. Any ideas?

```<code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <StackPanel>
      <TextBlock FontSize="50" RenderTransformOrigin=".5,.5">
         <TextBlock.Style>
            <Style>
               <Style.Triggers>
                  <DataTrigger Binding="{Binding IsChecked, ElementName=FlipX}" Value="True">
                     <Setter Property="RenderTransform.ScaleX" Value="-1"/>
                  </DataTrigger>
                  <DataTrigger Binding="{Binding IsChecked, ElementName=FlipY}" Value="True">
                     <Setter Property="RenderTransform.ScaleY" Value="-1"/>
                  </DataTrigger>
               </Style.Triggers>
            </Style>
         </TextBlock.Style>
         <TextBlock.RenderTransform>
          <ScaleTransform/>
         </TextBlock.RenderTransform>
      Hello World
      </TextBlock>
      <CheckBox Name="FlipX">Flip x</CheckBox>
      <CheckBox Name="FlipY">Flip y</CheckBox>
   </StackPanel>
</Page>
</code>```

答:
Either use animations, can be single frame & instant.

Or encapsulate some of this structure in the Template of a ContentControl. Then you can name the transform and you can try targeting it with the Setter.TargetName.

Body:
A failed XAML attempt here - I'm obviously doing something stupid with the Style/Setter syntax. I just want to flip an element based on some bindings by setting the ScaleX and ScaleY properties of a ScaleTransform from a DataTrigger. Setter.Property obviously doesn't support a property path, but how can I get round this? I can't set the whole RenderTransform property because ScaleX and ScaleY are independent. Any ideas?

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <StackPanel>
      <TextBlock FontSize="50" RenderTransformOrigin=".5,.5">
         <TextBlock.Style>

            </Style>
         </TextBlock.Style>
         <TextBlock.RenderTransform>
          <ScaleTransform/>
         </TextBlock.RenderTransform>
      Hello World
      </TextBlock>
      <CheckBox Name="FlipX">Flip x</CheckBox>
      <CheckBox Name="FlipY">Flip y</CheckBox>
   </StackPanel>
</Page>


问:
Not showing dropdown menu, and "Nothing Selected" message showing in title, please check code

I'm trying to do auto select the option in dropdown menu but it is not showing dropdown menu and displaing title="Nothing Selected". In my code I have written opt.setAttribute("selected", "selected");

答: To set the option as selected you only need selected not selected="selected".</p>


问:
tensorflow: Obtain RNN hidden states gradients with respect to input
My model consists of an Embedding layer and a SimpleRNN layer. I have obtained the hidden states at all steps with model.predict, and plotted them against the steps. I find that the hidden states converge to zero but I am not sure if I can infer anything from that. Therefore plotting their gradients with respect to the model inputs might provide me some further insights. I would like some help with obtaining these gradients.

My model:

```<code>batch_size = 9600   # batch size can take a smaller value, e.g. 100
inp= Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False, name= 'embedding')(inp)
rnn= SimpleRNN(200, return_sequences= True, return_state= False, stateful= True,
               batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

h0 = tf.random.uniform((batch_size, 200))
rnn_allstates = rnn(emb_out, initial_state=h0)
print(rnn_allstates.shape)   # (9600, 1403, 200)
model_rnn = Model(inputs=inp, outputs= rnn_allstates, name= 'model_rnn')
model_rnn.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model_rnn.summary()

>>>
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(9600, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (9600, 1403, 100)         4348900
_________________________________________________________________
simpleRNN (SimpleRNN)        (9600, 1403, 200)         60200
=================================================================
</code>```

Obtaining the hidden states:

```<code>rnn_ht = model_rnn.predict(xtr_pad)   # xtr_pad.shape = (9600,1403)
rnn_ht_red= np.mean(rnn_ht, 2)
rnn_ht_red= np.mean(rnn_ht_red,0)
steps= [t for t in range(1403)]
plt.plot(steps, rnn_ht_red, linestyle= 'dotted')

</code>```

Attempt to obtain gradients:

```<code>sess= k.get_session()
# The hidden states tf.Variable shaped (n_samples = 9600, n_steps = 1403, n_units = 200):
states_var= model_rnn.output
# A list of hidden states variable for all time steps, aggregated over samples and RNN units:
ht_vars= [states_var[:, t, :] for t in range(1403)]        # each item in list has shape (9600, 200)
ht_vars_agg= [tf.reduce_mean(ht,[0,1]) for ht in ht_vars]  # each item in list has shape (), because I wish to obtain a SINGLE gradient value at each time step.

# Create gradient function and feed data:
dhtdx_vars= [k.gradients(ht, model_rnn.input) for ht in ht_vars_agg]
dhtdx= [sess.run(pd, feed_dict={model_rnn.input: xtr_pad} ) for pd in dhtdx_vars  ]
</code>```

The following error points to the last line above

```<code>TypeError: Fetch argument None has invalid type <class 'NoneType'>
</code>```

Every backend gradient item in dhtdx_vars is [None]. When I remove the aggregation line the same error still persists.

An attempt with gradient tape also returns None Error in the computed gradient.

```<code>with tf.GradientTape() as tape:
    x= model_rnn.input
    ht = model_rnn(x)
grad = tape.gradient(ht, model_rnn.input)
</code>```

Thanks in advance for any help.

答:
The problem is tf.GradientTape() doesn't propagate the gradients through integer inputs. That is probably the reason you are getting None gradients. What you can do is calculate the gradients with respect to the output of the Embedding layer like this:

```<code>import tensorflow as tf

input_length = 1403
inp= tf.keras.layers.Input(shape= (input_length,))
emb_out= tf.keras.layers.Embedding(500, 100, input_length= input_length, trainable= False)(inp)
rnn_out = tf.keras.layers.SimpleRNN(200,  return_sequences = True)(emb_out)

model = tf.keras.Model(inputs=inp, outputs=rnn_out)
model.summary()

xte_pad = tf.random.uniform((10, 1403), maxval=500, dtype=tf.int32)
y = tf.random.normal((10, 1403, 200))
ds = tf.data.Dataset.from_tensor_slices((xte_pad, y)).batch(5)

embedding_layer = model.layers[1]
rnn_layer = model.layers[2]
epochs = 1
for epoch in range(epochs):
  for step, (x_batch_train, y_batch_train) in enumerate(ds):
    with tf.GradientTape() as tape:
        embedded_x = embedding_layer(x_batch_train)
        tape.watch(embedded_x)
        y = rnn_layer(embedded_x)

    grads = tape.gradient(y, embedded_x)
    tf.print(grads.shape)
</code>```
```<code>Model: "model_10"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_13 (InputLayer)       [(None, 1403)]            0

 embedding_12 (Embedding)    (None, 1403, 100)         50000

 simple_rnn_12 (SimpleRNN)   (None, 1403, 200)         60200

=================================================================
Total params: 110,200
Trainable params: 60,200
Non-trainable params: 50,000
_________________________________________________________________
TensorShape([5, 1403, 100])
TensorShape([5, 1403, 100])
</code>```

Body:
My model consists of an Embedding layer and a SimpleRNN layer. I have obtained the hidden states at all steps with model.predict, and plotted them against the steps. I find that the hidden states converge to zero but I am not sure if I can infer anything from that. Therefore plotting their gradients with respect to the model inputs might provide me some further insights. I would like some help with obtaining these gradients.

My model:

batch_size = 9600   # batch size can take a smaller value, e.g. 100
inp= Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False, name= 'embedding')(inp)
rnn= SimpleRNN(200, return_sequences= True, return_state= False, stateful= True,
               batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

h0 = tf.random.uniform((batch_size, 200))
rnn_allstates = rnn(emb_out, initial_state=h0)
print(rnn_allstates.shape)   # (9600, 1403, 200)
model_rnn = Model(inputs=inp, outputs= rnn_allstates, name= 'model_rnn')
model_rnn.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model_rnn.summary()

>>>
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(9600, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (9600, 1403, 100)         4348900
_________________________________________________________________
simpleRNN (SimpleRNN)        (9600, 1403, 200)         60200
=================================================================

Obtaining the hidden states:

rnn_ht = model_rnn.predict(xtr_pad)   # xtr_pad.shape = (9600,1403)
rnn_ht_red= np.mean(rnn_ht, 2)
rnn_ht_red= np.mean(rnn_ht_red,0)
steps= [t for t in range(1403)]
plt.plot(steps, rnn_ht_red, linestyle= 'dotted')

Attempt to obtain gradients:

sess= k.get_session()
# The hidden states tf.Variable shaped (n_samples = 9600, n_steps = 1403, n_units = 200):
states_var= model_rnn.output
# A list of hidden states variable for all time steps, aggregated over samples and RNN units:
ht_vars= [states_var[:, t, :] for t in range(1403)]        # each item in list has shape (9600, 200)
ht_vars_agg= [tf.reduce_mean(ht,[0,1]) for ht in ht_vars]  # each item in list has shape (), because I wish to obtain a SINGLE gradient value at each time step.

# Create gradient function and feed data:
dhtdx_vars= [k.gradients(ht, model_rnn.input) for ht in ht_vars_agg]
dhtdx= [sess.run(pd, feed_dict={model_rnn.input: xtr_pad} ) for pd in dhtdx_vars  ]

The following error points to the last line above

TypeError: Fetch argument None has invalid type <class 'NoneType'>

Every backend gradient item in dhtdx_vars is [None]. When I remove the aggregation line the same error still persists.

An attempt with gradient tape also returns None Error in the computed gradient.

with tf.GradientTape() as tape:
    x= model_rnn.input
    ht = model_rnn(x)
grad = tape.gradient(ht, model_rnn.input)

Thanks in advance for any help.

Body:
The problem is tf.GradientTape() doesn't propagate the gradients through integer inputs. That is probably the reason you are getting None gradients. What you can do is calculate the gradients with respect to the output of the Embedding layer like this:

import tensorflow as tf

input_length = 1403
inp= tf.keras.layers.Input(shape= (input_length,))
emb_out= tf.keras.layers.Embedding(500, 100, input_length= input_length, trainable= False)(inp)
rnn_out = tf.keras.layers.SimpleRNN(200,  return_sequences = True)(emb_out)

model = tf.keras.Model(inputs=inp, outputs=rnn_out)
model.summary()

xte_pad = tf.random.uniform((10, 1403), maxval=500, dtype=tf.int32)
y = tf.random.normal((10, 1403, 200))
ds = tf.data.Dataset.from_tensor_slices((xte_pad, y)).batch(5)

embedding_layer = model.layers[1]
rnn_layer = model.layers[2]
epochs = 1
for epoch in range(epochs):
  for step, (x_batch_train, y_batch_train) in enumerate(ds):
    with tf.GradientTape() as tape:
        embedded_x = embedding_layer(x_batch_train)
        tape.watch(embedded_x)
        y = rnn_layer(embedded_x)

    grads = tape.gradient(y, embedded_x)
    tf.print(grads.shape)

Model: "model_10"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_13 (InputLayer)       [(None, 1403)]            0

 embedding_12 (Embedding)    (None, 1403, 100)         50000

 simple_rnn_12 (SimpleRNN)   (None, 1403, 200)         60200

=================================================================
Total params: 110,200
Trainable params: 60,200
Non-trainable params: 50,000
_________________________________________________________________
TensorShape([5, 1403, 100])
TensorShape([5, 1403, 100])


问:
Is there any better way to carry out partial match of a vector of strings in c++?
I have two vectors of strings and want to carry out a partial/full match between each string i.e

```<code>std::vector<std::string> A = { "AA", "ABC" }
std::vector<std::string> B = { "AABB", "AABC", "ABC", "BC"}
</code>```

I want to perform a partial/full match for all strings in A with all strings in B.
Simplest approach would be just run loops over both vectors

```<code>for(const string& s1 : A)
{
  for(const string& s2 : B)
  {
    if(s2.find(s1) != std::string::npos)
      std::cout << "partial matched" << std::endl;
  }
}
</code>```

Results for the above example would be:

```<code>"AA"  --> "AABB", "AABC"
"ABC" --> "AABC", "ABC"
</code>```

Is there any better way to do this?

答:
The brute force method is by far the simplest. You can potentially make the code cleaner by using nested calls to std::any_of.

To be more efficient, you need to wade deep into complex string searching algorithms. I believe the state of the art in multiple-pattern search is Aho-Corasick. A variant is Commentz-Walter.

There's a BSD 2-clause (looks like)-licensed implementation of Aho-Corasick on Github, though you'd probably want to add a modified main searching function to immediately return if any match is found, instead of collecting all.

If you really want to wade deep into the reeds, you could start with this paper and follow the references.

Body:
I have two vectors of strings and want to carry out a partial/full match between each string i.e

std::vector<std::string> A = { "AA", "ABC" }
std::vector<std::string> B = { "AABB", "AABC", "ABC", "BC"}

I want to perform a partial/full match for all strings in A with all strings in B.
Simplest approach would be just run loops over both vectors

for(const string& s1 : A)
{
  for(const string& s2 : B)
  {
    if(s2.find(s1) != std::string::npos)
      std::cout << "partial matched" << std::endl;
  }
}

Results for the above example would be:

"AA"  --> "AABB", "AABC"
"ABC" --> "AABC", "ABC"

Is there any better way to do this?


问:
Apache Sqoop moved into the Attic in 2021-06
I have installed hadoop version 3.3.1 and sqoop 1.4.7 which doesn't seem  compatible , I am getting depreciated API implemented error while importing rdbms table.

As I tried to google for compatible versions I found apache sqoop is moved to appache attiq .and version 1.4.7 which is last stable version states in its documentation says  that "  Sqoop is currently supporting 4 major Hadoop releases - 0.20, 0.23, 1.0 and 2.0. "

Would you please explain what does it mean and what should I do.
could you please suggest What are the alternatives of SQOOP .

答:
It means just what the board minutes say: Sqoop has become inactive and is now moved to the Apache Attic. This doesn't mean Sqoop is deprecated in favor of some other project, but for practical purposes you should probably not build new implementations using it.

Much of the same functionality is available in other tools, including other Apache projects. Possible options are Spark, Kafka, Flume. Which one to use is very dependent on the specifics of your use case, since none of these quite fill the same niche as Sqoop. The database connectivity capabilities of Spark make it the most flexible solution, but it also could be the most labor-intensive to set up. Kafka might work, although it's not quite as ad-hoc friendly as Sqoop (take a look at Kafka Connect). I probably wouldn't use Flume, but it might be worth a look (it is mainly meant for shipping logs).


问:
How can I detect the browser back button with Vue?
In my component I need to do some logic when the user is navigate to my component using browser "back" button.

Maybe there is a property in vue router or something similar?

How can I detect the browser back button with Vue?

答:
You can use popstate event,

window.addEventListener('popstate', function(event) {
   // do something
   console.log(event);
});
```


问:
Add a column of buttons over an image in Flutter
I have a flutter app that I want to add "stories" to, but I am unable to do so cause I can't place 3 buttons over an image.

That's my desired look...

And this is what I can do so far...

And this is my code:-

```<code>

child: GestureDetector(
          child: Center(
            child: Stack(
              alignment: Alignment.bottomRight,
              children: [
                Image.network(
                  widget.url,
                ),
                Container(
                  child: Column(children: [
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    )
                  ]),
                )
              ],
            ),
          ),
          onTap: () => controller.next(),
        ),

</code>```

How can I achieve this effect?

Am I doing something with the Stack widget?

答:
The default mainAxisSize of Column is max, If you set MainAxisSize.min for all Column you will get Stack's alignment.

child: Column(
  mainAxisSize: MainAxisSize.min,
```
<p>As for the alignment of your desire UI, I prefer using <code>Align</code> widget to wrap the parent <code>Column</code>.</p>
<pre class="lang-dart prettyprint-override"><code>Align(
  alignment: Alignment(-1, .5), //play with it
  child: Container(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
</code>```

More about Align.

Body:
I have a flutter app that I want to add "stories" to, but I am unable to do so cause I can't place 3 buttons over an image.

That's my desired look...

And this is what I can do so far...

And this is my code:-

child: GestureDetector(
          child: Center(
            child: Stack(
              alignment: Alignment.bottomRight,
              children: [
                Image.network(
                  widget.url,
                ),
                Container(
                  child: Column(children: [
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    ),
                    Container(
                      color: Colors.grey,
                      child:
                          Column(children: [Icon(Icons.share), Text('مشاركة')]),
                    )
                  ]),
                )
              ],
            ),
          ),
          onTap: () => controller.next(),
        ),

How can I achieve this effect?

Am I doing something with the Stack widget?

Body:
The default mainAxisSize of Column is max, If you set MainAxisSize.min for all Column you will get Stack's alignment.

child: Column(
  mainAxisSize: MainAxisSize.min,

As for the alignment of your desire UI, I prefer using Align widget to wrap the parent Column.

Align(
  alignment: Alignment(-1, .5), //play with it
  child: Container(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [

More about Align.


问:
Getting nodes neighbors with the CGAL python binding
I'm trying to make a dictionary from my 2D Delaunay triangulation similar to : {node_index : [list of nodes neighbors]}. I'm using the cgal python binding to compute the Delaunay triangulation on a set of 2D point cloud.

Unfortunately I didn't find enough documentation in python on how to get each node's neighbors from the triangulation.

I would be very grateful if you could help me solve this issue

答:
You can use something like the following:

```<code>from CGAL.CGAL_Kernel import Point_2
from CGAL.CGAL_Triangulation_2 import Delaunay_triangulation_2
from CGAL.CGAL_Triangulation_2 import Delaunay_triangulation_2_Vertex_circulator

t = Delaunay_triangulation_2()

v1 = t.insert(Point_2(1, 2))
t.insert(Point_2(3, 2))
t.insert(Point_2(3, 44))
t.insert(Point_2(34, 4))
t.insert(Point_2(11, 45))
t.insert(Point_2(11, 7))

print("Nb vertices ", t.number_of_vertices())

circulator = t.incident_vertices(v1)
done = circulator.next()

while(1):
  v = circulator.next()
  print(v.point())
  if v == done:
    break
</code>```

incident_vertices() returns a circulator, i.e. an iterator that loops infinitely.

Body:
You can use something like the following:

from CGAL.CGAL_Kernel import Point_2
from CGAL.CGAL_Triangulation_2 import Delaunay_triangulation_2
from CGAL.CGAL_Triangulation_2 import Delaunay_triangulation_2_Vertex_circulator

t = Delaunay_triangulation_2()

v1 = t.insert(Point_2(1, 2))
t.insert(Point_2(3, 2))
t.insert(Point_2(3, 44))
t.insert(Point_2(34, 4))
t.insert(Point_2(11, 45))
t.insert(Point_2(11, 7))

print("Nb vertices ", t.number_of_vertices())

circulator = t.incident_vertices(v1)
done = circulator.next()

while(1):
  v = circulator.next()
  print(v.point())
  if v == done:
    break

incident_vertices() returns a circulator, i.e. an iterator that loops infinitely.


问:
Why can't I do this - Create a .net object and call one method all on one line
```<code>(New clsViewIllus).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)
</code>```

<p>... in VB? Basically too lazy to do this:</p>

```<code>Dim vi As New clsViewIllus
vi.View(MyIBaseView, enumViewSolveTypes.View, Me, , True)
</code>```

答:
clsViewIllus should be a shared class. You mentioned in comments that the class has other uses and ways to use the methods. But do those other uses stay in context with the method you have defined?

If not, then you need to write another class.

Now, to your question:

Why can't I:

```<code>(New clsViewIllus).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)
</code>```

Edit

Basically, it isn't allowed from what I can tell. If I can find something in the language specification, I will update. But the compiler pretty much tells you why this can't be done:

I made a mistake on my side:

I believe you can. I did it in C#. What you may be missing is the parentheses. Try this:

```<code>(New clsViewIllus()).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)
</code>```

Although, IMHO, it is bad form and screams for Module or Shared.

Body:
(New clsViewIllus).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)

... in VB? Basically too lazy to do this:

Dim vi As New clsViewIllus
vi.View(MyIBaseView, enumViewSolveTypes.View, Me, , True)

Body:
clsViewIllus should be a shared class. You mentioned in comments that the class has other uses and ways to use the methods. But do those other uses stay in context with the method you have defined?

If not, then you need to write another class.

Now, to your question:

Why can't I:

(New clsViewIllus).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)

Edit

Basically, it isn't allowed from what I can tell. If I can find something in the language specification, I will update. But the compiler pretty much tells you why this can't be done:

I made a mistake on my side:

I believe you can. I did it in C#. What you may be missing is the parentheses. Try this:

(New clsViewIllus()).View(MyIBaseView, enumViewSolveTypes.View, Me, , True)

Although, IMHO, it is bad form and screams for Module or Shared.


问:
How to pivot value of JSON in a DataFrame
I have an original DataFrame that contain a list of JSON in each record

Here is an example of the DataFrame

```<code>import pandas as pd
d = [{
    'id': 'abcd1234',
    'property_name':'a',
    'timestamp':'2021:12:10',
    'raw_data': [
        {
        'key1':'value1',
        'key2':'value2'
    },
    {
        'key3':'value3',
        'key4':'value4'
    }]

},
{   'id':'efgh5678',
    'property_name':'b',
    'timestamp':'2021:12:12',
    'raw_data': [{
        'key5':'value5',
        'key6':'value6'
    }]
}]
df = pd.DataFrame(d)
</code>```

Here is the output of DataFrame

```<code>id  property_name   timestamp   raw_data
0   abcd1234    a   2021:12:10  [{'key1': 'value1', 'key2': 'value2'}, {'key3': 'value3', 'key4': 'value4'}]
1   efgh5678    b   2021:12:12  [{'key5': 'value5', 'key6': 'value6'}]
</code>```

Now, I want to transform this DataFrame with the following condition,

Pivot the keys of JSON as a column and value of the JSON as a value

Have some prefix of the columns name based on 'property_name' field

For a record with absence value, make it NULL

Here is a desired final DataFrame

```<code>id  property_name   timestamp   a_key1  a_key2  a_key3  a_key4  b_key5  b_key6
0   abcd1234    a   2021:12:10  value1  value2  value3  value4  NaN     NaN
1   efgh5678    b   2021:12:12  NaN     NaN     NaN      NaN    value5  value6
</code>```

So far, I have succeeded it with for loop in each record which is not quite efficient way to achieve since the DataFrame is expected to grow exponentially. Anyway to make this function in the efficient way?

Ps1. The following is the coded that I am using

```<code>raw_data = pd.DataFrame()
for idx,val in df["raw_data"].iteritems():
    the_list = json.loads(val)
    temp = pd.DataFrame(the_list, index=[idx]*len(the_list))
    temp['key'] = stg1.loc[idx, 'raw_data'] + '_' + temp['key']
    raw_data = pd.concat([raw_data,temp], axis=0)

raw_data = raw_data.set_index("property_name",append=True).unstack()
raw_data.columns = raw_data.columns.droplevel(0)
final = df[['uid', 'property_name', 'timestamp']].join(raw_data)
</code>```

Ps2. Apologize for the unclear DataFrame format. This is the first time I post on Stack overflow and I don't figure out how to post pretty format of DataFrame.

答:
You could first modify the dicts in "raw_data" to include the property names in the keys. Then set_index with the column names other than "raw_data", then explode the "raw_data" column. Then convert the resulting Series to a DataFrame, groupby + first to get a single row for each property name.

```<code>df['raw_data'] = [[{f'{pn}_{k}': v for k,v in d.items()} for d in lst] for pn, lst in zip(df['property_name'], df['raw_data'])]
s = df.set_index(df.columns.drop('raw_data').tolist())['raw_data'].explode()
out = pd.DataFrame(s.tolist(), index=s.index).groupby(level=[0,1,2]).first().reset_index().fillna(np.nan)
</code>```

Output:

```<code>         id property_name   timestamp  a_key1  a_key2  a_key3  a_key4  b_key5   b_key6
0  abcd1234             a  2021:12:10  value1  value2  value3  value4     NaN      NaN
1  efgh5678             b  2021:12:12     NaN     NaN     NaN     NaN  value5   value6
</code>```

Body:
I have an original DataFrame that contain a list of JSON in each record

Here is an example of the DataFrame

import pandas as pd
d = [{
    'id': 'abcd1234',
    'property_name':'a',
    'timestamp':'2021:12:10',
    'raw_data': [
        {
        'key1':'value1',
        'key2':'value2'
    },
    {
        'key3':'value3',
        'key4':'value4'
    }]

},
{   'id':'efgh5678',
    'property_name':'b',
    'timestamp':'2021:12:12',
    'raw_data': [{
        'key5':'value5',
        'key6':'value6'
    }]
}]
df = pd.DataFrame(d)

Here is the output of DataFrame

id  property_name   timestamp   raw_data
0   abcd1234    a   2021:12:10  [{'key1': 'value1', 'key2': 'value2'}, {'key3': 'value3', 'key4': 'value4'}]
1   efgh5678    b   2021:12:12  [{'key5': 'value5', 'key6': 'value6'}]

Now, I want to transform this DataFrame with the following condition,

Pivot the keys of JSON as a column and value of the JSON as a value

Have some prefix of the columns name based on 'property_name' field

For a record with absence value, make it NULL

Here is a desired final DataFrame

id  property_name   timestamp   a_key1  a_key2  a_key3  a_key4  b_key5  b_key6
0   abcd1234    a   2021:12:10  value1  value2  value3  value4  NaN     NaN
1   efgh5678    b   2021:12:12  NaN     NaN     NaN      NaN    value5  value6

So far, I have succeeded it with for loop in each record which is not quite efficient way to achieve since the DataFrame is expected to grow exponentially. Anyway to make this function in the efficient way?

Ps1. The following is the coded that I am using

raw_data = pd.DataFrame()
for idx,val in df["raw_data"].iteritems():
    the_list = json.loads(val)
    temp = pd.DataFrame(the_list, index=[idx]*len(the_list))
    temp['key'] = stg1.loc[idx, 'raw_data'] + '_' + temp['key']
    raw_data = pd.concat([raw_data,temp], axis=0)

raw_data = raw_data.set_index("property_name",append=True).unstack()
raw_data.columns = raw_data.columns.droplevel(0)
final = df[['uid', 'property_name', 'timestamp']].join(raw_data)

Ps2. Apologize for the unclear DataFrame format. This is the first time I post on Stack overflow and I don't figure out how to post pretty format of DataFrame.

Body:
You could first modify the dicts in "raw_data" to include the property names in the keys. Then set_index with the column names other than "raw_data", then explode the "raw_data" column. Then convert the resulting Series to a DataFrame, groupby + first to get a single row for each property name.

df['raw_data'] = [[{f'{pn}_{k}': v for k,v in d.items()} for d in lst] for pn, lst in zip(df['property_name'], df['raw_data'])]
s = df.set_index(df.columns.drop('raw_data').tolist())['raw_data'].explode()
out = pd.DataFrame(s.tolist(), index=s.index).groupby(level=[0,1,2]).first().reset_index().fillna(np.nan)

Output:

         id property_name   timestamp  a_key1  a_key2  a_key3  a_key4  b_key5   b_key6
0  abcd1234             a  2021:12:10  value1  value2  value3  value4     NaN      NaN
1  efgh5678             b  2021:12:12     NaN     NaN     NaN     NaN  value5   value6


问:
JS How to get the deepest (last) children of a node
I want to get all children of a node and use .click() method on them in JS.

答:
I didn't found any better than write this script, hope it help someone:

```<code>const getLastChildren = (parent: Element): Element[] => {
  return Array.from(parent.children).reduce<Element[]>((acc, node) => {
    const children = Array.from(node.children);
    if (children.length === 0) {
      acc.push(node);
      return acc;
    }
    return [...acc, ...getLastChildren(node)];
  }, []);
};
</code>```

(without typescript):

```<code>const getLastChildren = (parent) => {
  return Array.from(parent.children).reduce((acc, node) => {
    const children = Array.from(node.children);
    if (children.length === 0) {
      acc.push(node);
      return acc;
    }
    return [...acc, ...getLastChildren(node)];
  }, []);
};
</code>```

Body:
I didn't found any better than write this script, hope it help someone:

const getLastChildren = (parent: Element): Element[] => {
  return Array.from(parent.children).reduce<Element[]>((acc, node) => {
    const children = Array.from(node.children);
    if (children.length === 0) {
      acc.push(node);
      return acc;
    }
    return [...acc, ...getLastChildren(node)];
  }, []);
};

(without typescript):

const getLastChildren = (parent) => {
  return Array.from(parent.children).reduce((acc, node) => {
    const children = Array.from(node.children);
    if (children.length === 0) {
      acc.push(node);
      return acc;
    }
    return [...acc, ...getLastChildren(node)];
  }, []);
};


问:
change font xamarin.android c#
I want to change the font of the whole project in Xamarin.Android & visual studio, but unfortunately I can only change the font of a textview using typeface. And this solution is not enough to solve my project. Is there a solution to change the font of the whole program?

Of course, based on the questions that were available, I decided to add the font in a folder called font in the project and defined it in style.xml as follows.

```<code><style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:fontFamily">@font/shabnam</item>
        <item name="android:typeface">@font/shabnam</item>
    </style>
</code>```

But when running the program, it showed me the following error

resource font/shabnam (aka com.companyname.yeti:font/shabnam) not found.

```<code>thank you for your help
</code>```

答:
You could set the font for the Theme which you set in MainActivity.

Check the Theme in MainActivity:

```<code>  [Activity(Label = "App3", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
</code>```

Set the font in Resources> values> styles.xml

```<code> <style name="MainTheme" parent="MainTheme.Base">

<item name="android:fontFamily">@font/amtrash</item>
</style>
</code>```

font is the folder name which i created in Resource folder to put the font .tff file.

Title: change font xamarin.android c#

Body:
I want to change the font of the whole project in Xamarin.Android & visual studio, but unfortunately I can only change the font of a textview using typeface. And this solution is not enough to solve my project. Is there a solution to change the font of the whole program?

Of course, based on the questions that were available, I decided to add the font in a folder called font in the project and defined it in style.xml as follows.

But when running the program, it showed me the following error

resource font/shabnam (aka com.companyname.yeti:font/shabnam) not found.

thank you for your help

Body:
You could set the font for the Theme which you set in MainActivity.

Check the Theme in MainActivity:

  [Activity(Label = "App3", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]

Set the font in Resources> values> styles.xml

 <style name="MainTheme" parent="MainTheme.Base">

<item name="android:fontFamily">@font/amtrash</item>
</style>

font is the folder name which i created in Resource folder to put the font .tff file.


问:
Extract only 1 month from a multi-year netcdf file
I am quite new to programming and I wanted to know if you could help me. I have a file that contains daily precipitation data from 2000 to 2020. I think with pandas I could create a dataframe that contains only the values of the month of January but I can't understand how. Or maybe with CDO create a new file that only contains those values. Could someone help me? I would appreciate it

答:
The cdo solution would be

```<code>cdo selmon,n in.nc out.nc
</code>```

where n is the number of the month, in your case n=1, so

```<code>cdo selmon,1 in.nc out.nc
</code>```

You can also specify a list of months or a range using the forward slash, e.g.

```<code>cdo selmon,3/5 in.nc out.nc
</code>```

Body:
The cdo solution would be

cdo selmon,n in.nc out.nc

where n is the number of the month, in your case n=1, so

cdo selmon,1 in.nc out.nc

You can also specify a list of months or a range using the forward slash, e.g.

cdo selmon,3/5 in.nc out.nc


问:
How to pass textview value from adapter class to texview of another acivity
I want to pass the value of textview from the adapter class to another textview of another activity.
please help me ...

//recycleradapter class

```<code>Intent intent = new Intent(applicationContext, DetailActivity.class);

            intent.putExtra("likes",holder.quantity.toString());
            applicationContext.startActivity(intent);
</code>```

// detail acivity class

```<code>String like = getIntent().getStringExtra("Likes");
Toast.makeText(this, like+"", Toast.LENGTH_SHORT).show();
item_quantiy.setText(like);
</code>```

答:
Do it in two steps.

get the value from the adapter to the activity

Then send the data from this activity to the other

Use an interface to trigger when the item in the recyclerview in clicked

In the interface implementation in the activity get that data and pass it to the next activity via an intent like you're doing here

Body:
I want to pass the value of textview from the adapter class to another textview of another activity.
please help me ...

//recycleradapter class

Intent intent = new Intent(applicationContext, DetailActivity.class);

            intent.putExtra("likes",holder.quantity.toString());
            applicationContext.startActivity(intent);

// detail acivity class

String like = getIntent().getStringExtra("Likes");
Toast.makeText(this, like+"", Toast.LENGTH_SHORT).show();
item_quantiy.setText(like);


问:
While loop on a mysql call is throwing unknown PDO exception 'General Error'
I use the following (or similar) code on hundreds of pages I have built:

```<code>$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

while($row = $stmt->fetch()) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}
</code>```

Out of nowwhere, I started receiving the following error on a few pages:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error' in C:....page.php:28 Stack trace: #0
  C:..page.php(28): PDOStatement->fetch() #1 {main} thrown

The first loop will run (with no problem) but gives an error AFTER the first loop. The error code (line 28) references the line:

```<code>while($row = $stmt->fetch()) {
</code>```

I have never seen this before. As a test, I modified the code to store all returned results as:

```<code>$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

$rows = $stmt->fetchALL();

foreach($rows as $row) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}
</code>```

and the system works. Any idea as to why?

答:
Unless this is merely a typo in your question, your arrow operator is incomplete.</p>

```<code>$stmt>execute();

// Should be
$stmt->execute();
</code>```

Body:
I use the following (or similar) code on hundreds of pages I have built:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

while($row = $stmt->fetch()) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}

Out of nowwhere, I started receiving the following error on a few pages:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error' in C:....page.php:28 Stack trace: #0
  C:..page.php(28): PDOStatement->fetch() #1 {main} thrown

The first loop will run (with no problem) but gives an error AFTER the first loop. The error code (line 28) references the line:

while($row = $stmt->fetch()) {

I have never seen this before. As a test, I modified the code to store all returned results as:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

$rows = $stmt->fetchALL();

foreach($rows as $row) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}

and the system works. Any idea as to why?

Body:
Unless this is merely a typo in your question, your arrow operator is incomplete.

$stmt>execute();

// Should be
$stmt->execute();


问:
Run scheduled task inside Pod in Kubernetes
I have a small instance of influxdb running in my kubernetes cluster.

The data of that instance is stored in a persistent storage.

But I also want to run the backup command from influx at scheduled interval.

```<code>influxd backup -portable /backuppath
</code>```

What I do now is exec into the pod and run it manually.

Is there a way that I can do this automatically?

答:
CronJob is the way to go here. It acts more or less like a crontab, but for Kubernetes.

As an example you could use this

apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup
spec:
  schedule: 0 8 * * *
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: influxdb-backup
            image: influxdb
            imagePullPolicy: IfNotPresent
            command: ["/bin/sh"]
            args:
            - "-c"
            - "influxd backup -portable /backuppath"
          restartPolicy: Never
```

This will create a Job, everyday at 08:00, executing influxd backup -portable /backuppath. Of course, you have to edit it accordingly, to work on your environment.

Body:
I have a small instance of influxdb running in my kubernetes cluster.

The data of that instance is stored in a persistent storage.

But I also want to run the backup command from influx at scheduled interval.

influxd backup -portable /backuppath

What I do now is exec into the pod and run it manually.

Is there a way that I can do this automatically?

Body:
CronJob is the way to go here. It acts more or less like a crontab, but for Kubernetes.

As an example you could use this

apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup
spec:
  schedule: 0 8 * * *
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: influxdb-backup
            image: influxdb
            imagePullPolicy: IfNotPresent
            command: ["/bin/sh"]
            args:
            - "-c"
            - "influxd backup -portable /backuppath"
          restartPolicy: Never

This will create a Job, everyday at 08:00, executing influxd backup -portable /backuppath. Of course, you have to edit it accordingly, to work on your environment.


问:
Convert multi nested Json to Pandas DataFrame
```<code>{
"ABC": {
"A": {
"Date": "01/01/2021",
"Value": "0.09"
},
"B": {
"Date": "01/01/2021",
"Value": "0.001"
}
},
"XYZ": {
"A": {
"Date": "01/01/2021",
"Value": "0.006"
},
"B": {
"Date": "01/01/2021",
"Value": "0.000"
}
}
}
</code>```

Current output after applying pd.json_normalize(x,max_level=1)

Expected Output :
Need to Convert this to pandas DataFrame

If any one can help or give some advice on working with this data that would be great!

答:
Use the following while the js is your input dict:

```<code>s = pd.DataFrame(js)
ss = s.apply(lambda x: [pd.Series(y)['Value'] for y in x])
ss['Date'] = s['ABC'].apply(pd.Series)['Date']
</code>```

result:

Body:
{
"ABC": {
"A": {
"Date": "01/01/2021",
"Value": "0.09"
},
"B": {
"Date": "01/01/2021",
"Value": "0.001"
}
},
"XYZ": {
"A": {
"Date": "01/01/2021",
"Value": "0.006"
},
"B": {
"Date": "01/01/2021",
"Value": "0.000"
}
}
}

Current output after applying pd.json_normalize(x,max_level=1)

Expected Output :
Need to Convert this to pandas DataFrame

If any one can help or give some advice on working with this data that would be great!

Body:
Use the following while the js is your input dict:

s = pd.DataFrame(js)
ss = s.apply(lambda x: [pd.Series(y)['Value'] for y in x])
ss['Date'] = s['ABC'].apply(pd.Series)['Date']

result:


问:
How do you click on an element with text in Puppeteer?
Is there any method or solution to click on an element with text? I couldn't find one in the API.

For example I have the following HTML:

    <button>Button text</button>
    Href text

Div text

```
<p>And I want to click on an element in which text is wrapped (click on the button inside <code>.elements</code>), like so:</p>
<pre class="lang-js prettyprint-override"><code>Page.click('Button text', '.elements')
</code>```

答:
With puppeteer 12.0.1, the following works for me:</p>
```<code>await page.click("input[value='Opt1']"); //where value is an attribute of the element input
await page.waitForTimeout(1000);

await page.click("li[value='Nested choice 1']"); //where value is an attribute of the element li after clicking the previous option
await page.waitForTimeout(5000);
</code>```

Body:
Is there any method or solution to click on an element with text? I couldn't find one in the API.

For example I have the following HTML:

    <button>Button text</button>
    Href text

Div text

And I want to click on an element in which text is wrapped (click on the button inside .elements), like so:

Page.click('Button text', '.elements')

Body:
With puppeteer 12.0.1, the following works for me:

await page.click("input[value='Opt1']"); //where value is an attribute of the element input
await page.waitForTimeout(1000);

await page.click("li[value='Nested choice 1']"); //where value is an attribute of the element li after clicking the previous option
await page.waitForTimeout(5000);