问:
Porting an C++ code application from Solaris to Linux and real time headers issues
Please help, The tools that I am using are kdevelop and qt4. On my main.cpp have errors, for example;

Error: sys/procset.h: No such files or directory
Error: sys/priocntl.h: No such files or directory
Error: sys/tspriocntl.h: No such files or directory
Error: sys/rtpriocntl.h: No such files or directory
In function 'int main(int. char**)':
Error: 'pcparms_t' was not declared in this scope
Error: expected ';' before 'pcparms'
Error: 'rtparms_t' was not declared in this scope
Error: 'rtparmsp' was not declared in this scope
Error: 'pcinfo_t' was not declared in this scope
Error: expected ';' before 'pcinfo'
Error: 'rtinfo_t' was not declared in this scope
Error: 'rtinfop' was not declared in this scope
warning: unused variable 'lret'
warning: unused variable 'priority'
...
...
...
*Exited with Status:2 *

I can't find real time those headers on my Centos 5 Linux.  Plus, I don't know the equivalence of those above headers for Linux.  I know I have to add an If statement for Solaris and Linux for the include headers, and I don't know which headers will be included on the if/else statement.

  When I remove headers by comment them out the real time headers and function for realtime function for solaris, I get it to run.

//pcparms_t pcparms;
//rtparms_t *rtparmsp;
//pcinfo_t pcinfo;
//rtinfo_t *rtinfop;

 My problem is what are the real time headers and functions for Linux or equivalent to Linux. My application code is a mix between c++ and qt4.  On the side of qt4 is their a need to use Real Time functions? On the c++ from Solaris do I need real time functions? If yes, where can I find them or what are they call and where do I place them?

答:
This is not really a QT related question but more of a porting Solaris->Linux question.

```<code>sys/procset.h
sys/priocntl.h
sys/tspriocntl.h
sys/rtpriocntl.h
</code>```

Those files are all Solaris specific system calls. They are part of priocntlset - generalized process scheduler control.

From the manpage

```<code>priocntlset(2)           System Calls           priocntlset(2)

NAME
       priocntlset - generalized process scheduler control

SYNOPSIS
       #include <sys/types.h>
       #include <sys/procset.h>
       #include <sys/priocntl.h>
       #include <sys/rtpriocntl.h>
       #include <sys/tspriocntl.h>
       #include <sys/iapriocntl.h>
       #include <sys/fsspriocntl.h>
       #include <sys/fxpriocntl.h>

       long priocntlset(procset_t *psp, int cmd, /* arg */ ...);

DESCRIPTION
       The priocntlset() function changes the scheduling properties of running
       processes. priocntlset() has the same functions as the priocntl() func-
       tion,  but  a more general way of specifying the set of processes whose
       scheduling properties are to be changed.

NOTES
    Due to the lack of a priocntl() system call on Linux and FreeBSD...
</code>```

The way in which processes are handled between Solaris and Linux is different. Both systems are variants of Unix, but the specific system calls you are looking for do not have a Linux equivalent. Basically priocntlset is used to (re)schedule processes. I am not up to date on the latest Linux Kernel, or what schedulers are available anymore, but any good book on a 2.6 (or 2.4) Kernel will have a section on scheduling with examples.

A good place to start on a Linux machine would be man syscalls.

Body:
This is not really a QT related question but more of a porting Solaris->Linux question.

sys/procset.h
sys/priocntl.h
sys/tspriocntl.h
sys/rtpriocntl.h

Those files are all Solaris specific system calls. They are part of priocntlset - generalized process scheduler control.

From the manpage

priocntlset(2)           System Calls           priocntlset(2)

NAME
       priocntlset - generalized process scheduler control

SYNOPSIS
       #include <sys/types.h>
       #include <sys/procset.h>
       #include <sys/priocntl.h>
       #include <sys/rtpriocntl.h>
       #include <sys/tspriocntl.h>
       #include <sys/iapriocntl.h>
       #include <sys/fsspriocntl.h>
       #include <sys/fxpriocntl.h>

       long priocntlset(procset_t *psp, int cmd, /* arg */ ...);

DESCRIPTION
       The priocntlset() function changes the scheduling properties of running
       processes. priocntlset() has the same functions as the priocntl() func-
       tion,  but  a more general way of specifying the set of processes whose
       scheduling properties are to be changed.

NOTES
    Due to the lack of a priocntl() system call on Linux and FreeBSD...

The way in which processes are handled between Solaris and Linux is different. Both systems are variants of Unix, but the specific system calls you are looking for do not have a Linux equivalent. Basically priocntlset is used to (re)schedule processes. I am not up to date on the latest Linux Kernel, or what schedulers are available anymore, but any good book on a 2.6 (or 2.4) Kernel will have a section on scheduling with examples.

A good place to start on a Linux machine would be man syscalls.


来源: stackexchange

问:
PHP MySQL PDO Connection to Google Cloud SQL Instance from VM Instance not working
DSN is:
mysql:dbname='MyDB';unix_socket='/cloudsql/ethereal-accord-123456789:us-central1:dev-Instance'

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

PDO Connection Code:

```<code> try {
              $conn = new PDO($dsn, $username, $password);
              // set the PDO error mode to exception

              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

              echo "Connected successfully";
              return $conn;

            } catch(PDOException $e) {
              echo "Connection failed: " . $e->getMessage().' <BR>';

            }
</code>```

I Cannot seem to find detail information on how to setup the connections correctly.
I follow all documents and activated the permissions for the VM IP, the Client SQL API, and Admin API, and nothing..

Any Help will be appreciated.

答:
You don't run the cloudsql proxy or you have defined another location for the socket file. You should check this.

```<code>./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=DATABASE_NAME';
</code>```

https://cloud.google.com/sql/docs/mysql/connect-external-app#pdo-tcp

ContentLicense: CC BY-SA 4.0

Body:
DSN is:
mysql:dbname='MyDB';unix_socket='/cloudsql/ethereal-accord-123456789:us-central1:dev-Instance'

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

PDO Connection Code:

 try {
              $conn = new PDO($dsn, $username, $password);
              // set the PDO error mode to exception

              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

              echo "Connected successfully";
              return $conn;

            } catch(PDOException $e) {
              echo "Connection failed: " . $e->getMessage().'
';

            }

I Cannot seem to find detail information on how to setup the connections correctly.
I follow all documents and activated the permissions for the VM IP, the Client SQL API, and Admin API, and nothing..

Any Help will be appreciated.

Body:
You don't run the cloudsql proxy or you have defined another location for the socket file. You should check this.

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=DATABASE_NAME';

https://cloud.google.com/sql/docs/mysql/connect-external-app#pdo-tcp


问:
Why does one variable get the same value as another value
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

```<code>void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}

</code>```

答:
C/C++ local variables are given memory when it is needed. Here the secret variable doesn't have any memory assigned. So it is actually following the address of x here. Look at this code here,

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

void a(){
    int x = 40;
    int y=30;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void b(){
    int xx;
    int z;
    printf( "This function believes that the other functions secret is: %d !\n", xx);
    printf("%d\n",z);
}

int main(){
    a();
    b();
    return 0;
}
</code>```

Here the secret is getting value of x and z is getting value of y. If you change the value of secret in the function b then this will assign a new memory for the variable secret.

Body:
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}

Body:
C/C++ local variables are given memory when it is needed. Here the secret variable doesn't have any memory assigned. So it is actually following the address of x here. Look at this code here,

#include<stdio.h>

void a(){
    int x = 40;
    int y=30;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void b(){
    int xx;
    int z;
    printf( "This function believes that the other functions secret is: %d !\n", xx);
    printf("%d\n",z);
}

int main(){
    a();
    b();
    return 0;
}

Here the secret is getting value of x and z is getting value of y. If you change the value of secret in the function b then this will assign a new memory for the variable secret.


问:
How to override X-Frame-Options for a controller or action in Rails 4
Rails 4 appears to set a default value of SAMEORIGIN for the X-Frame-Options HTTP response header. This is great for security, but it does not allow for parts of your app to be available in an iframe on a different domain.

You can override the value of X-Frame-Options globally using the config.action_dispatch.default_headers setting:

```<code>config.action_dispatch.default_headers['X-Frame-Options'] = "ALLOW-FROM https://apps.facebook.com"
</code>```

But how do you override it for just a single controller or action?

答:
I just wanted to include an updated answer here for anyone who finds this link when trying to figure out how to allow your Rails app to be embedded in an I-Frame and running into issues.

As of writing this, May 28th 2020, the X-Frame-Options changes are probably not your best solution to your problem. The "ALLOW-FROM" option has been totally disallowed by all major browsers.

The modern solution is to implement a Content-Security-Policy and set a 'frame_ancestors' policy. The 'frame_ancestors' key designates what domains can embed your app as an iframe. Its currently supported by major browsers and overrides your X-Frame-Options. This will allow you to prevent Clickjacking (which the X-Frame-Options was originally intended to help with before it largely became deprecated) and lock down your app in a modern environment.

You can set up a Content-Security-Policy with Rails 5.2 in an initializer (example below), and for Rails < 5.2 you can use a gem like the Secure Headers gem: https://github.com/github/secure_headers

You can also override the policy specifications on a controller/action basis if you'd like.

Content-Security-Policies are great for advanced security protections. Check out all the things you can configure in the Rails docs: https://edgeguides.rubyonrails.org/security.html

A Rails 5.2 example for a Content-Security-Policy:

```<code># config/initializers/content_security_policy.rb
    Rails.application.config.content_security_policy do |policy|
      policy.frame_ancestors :self, 'some_website_that_embeds_your_app.com'
    end
</code>```

An example of a controller specific change to a policy:

```<code># Override policy inline
class PostsController < ApplicationController
  content_security_policy do |p|
    p.frame_ancestors :self, 'some_other_website_that_can_embed_posts.com'
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Rails 4 appears to set a default value of SAMEORIGIN for the X-Frame-Options HTTP response header. This is great for security, but it does not allow for parts of your app to be available in an iframe on a different domain.

You can override the value of X-Frame-Options globally using the config.action_dispatch.default_headers setting:

config.action_dispatch.default_headers['X-Frame-Options'] = "ALLOW-FROM https://apps.facebook.com"

But how do you override it for just a single controller or action?

Body:
I just wanted to include an updated answer here for anyone who finds this link when trying to figure out how to allow your Rails app to be embedded in an I-Frame and running into issues.

As of writing this, May 28th 2020, the X-Frame-Options changes are probably not your best solution to your problem. The "ALLOW-FROM" option has been totally disallowed by all major browsers.

The modern solution is to implement a Content-Security-Policy and set a 'frame_ancestors' policy. The 'frame_ancestors' key designates what domains can embed your app as an iframe. Its currently supported by major browsers and overrides your X-Frame-Options. This will allow you to prevent Clickjacking (which the X-Frame-Options was originally intended to help with before it largely became deprecated) and lock down your app in a modern environment.

You can set up a Content-Security-Policy with Rails 5.2 in an initializer (example below), and for Rails < 5.2 you can use a gem like the Secure Headers gem: https://github.com/github/secure_headers

You can also override the policy specifications on a controller/action basis if you'd like.

Content-Security-Policies are great for advanced security protections. Check out all the things you can configure in the Rails docs: https://edgeguides.rubyonrails.org/security.html

A Rails 5.2 example for a Content-Security-Policy:

# config/initializers/content_security_policy.rb
    Rails.application.config.content_security_policy do |policy|
      policy.frame_ancestors :self, 'some_website_that_embeds_your_app.com'
    end

An example of a controller specific change to a policy:

# Override policy inline
class PostsController < ApplicationController
  content_security_policy do |p|
    p.frame_ancestors :self, 'some_other_website_that_can_embed_posts.com'
  end
end


问:
Java - [SQLITE_BUSY] The database file is locked (database is locked)
I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.

```<code>org.sqlite.SQLiteException: [SQLITE_BUSY]  The database file is locked (database is locked)
</code>```

I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)

I have these at start of my class;

```<code>private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
</code>```

Methods for example;

```<code>public int lastPlaceProgram(){

    String query= "Select * from userprogram where laststayed = 1";
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery(query);
        int programid = 0;
        while(rs.next()){
            programid = rs.getInt("programid");
        }
        return programid;
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
        return 0;
    }

}
</code>```

or

```<code>public String programType(int programid){
    String query = "Select * from programs where id = ?";
    try {
        preparedStatement = con.prepareStatement(query);
        preparedStatement.setInt(1, programid);
        ResultSet rs = preparedStatement.executeQuery();
        String type = "";
        while(rs.next()){

            type = rs.getString("type");
        }
        return type;
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

}
</code>```

And constructor;

```<code>public Operations() {
    String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
    try {
        con = DriverManager.getConnection(url);
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
</code>```

I tried to add these finally block to after catch blocks of all my 30 methods;

```<code>finally{
    try{
      con.close();
    } catch(Exception e){
    }
}
</code>```

But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.

答: Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.</p>

Body:
I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.

org.sqlite.SQLiteException: [SQLITE_BUSY]  The database file is locked (database is locked)

I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)

I have these at start of my class;

private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;

Methods for example;

public int lastPlaceProgram(){

    String query= "Select * from userprogram where laststayed = 1";
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery(query);
        int programid = 0;
        while(rs.next()){
            programid = rs.getInt("programid");
        }
        return programid;
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
        return 0;
    }

}

or

public String programType(int programid){
    String query = "Select * from programs where id = ?";
    try {
        preparedStatement = con.prepareStatement(query);
        preparedStatement.setInt(1, programid);
        ResultSet rs = preparedStatement.executeQuery();
        String type = "";
        while(rs.next()){

            type = rs.getString("type");
        }
        return type;
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

}

And constructor;

public Operations() {
    String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
    try {
        con = DriverManager.getConnection(url);
    } catch (SQLException ex) {
        Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

I tried to add these finally block to after catch blocks of all my 30 methods;

finally{
    try{
      con.close();
    } catch(Exception e){
    }
}

But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.


问:
Plotting multiple values to one key in python
I am trying to make a scatter plot with this dictionary

```<code>d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
</code>```

I want the keys to be in X-axis and the values to be on Y-axis, and also to show a legend with different key values. I have tried this code-

```<code>import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
colors = list("rgbk")
x, y =[], []
for i in d.keys():
   for j in d[i]:
       x.append(i)
       y.append(j)
   plt.scatter(x, y, color = colors.pop())
   plt.legend(d.keys())
plt.show()
</code>```

But this is giving me a plot with points with only one colour but the legends are alright.

答:
Here's a way:</p>

```<code>import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}

for i in d.keys():
   for j in d[i]:
       plt.scatter(i,j,color=(i/10,i/10,i/10))
   plt.legend(d.keys())
plt.show()
</code>```

Body:
I am trying to make a scatter plot with this dictionary

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}

I want the keys to be in X-axis and the values to be on Y-axis, and also to show a legend with different key values. I have tried this code-

import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
colors = list("rgbk")
x, y =[], []
for i in d.keys():
   for j in d[i]:
       x.append(i)
       y.append(j)
   plt.scatter(x, y, color = colors.pop())
   plt.legend(d.keys())
plt.show()

But this is giving me a plot with points with only one colour but the legends are alright.

Body:
Here's a way:

import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}

for i in d.keys():
   for j in d[i]:
       plt.scatter(i,j,color=(i/10,i/10,i/10))
   plt.legend(d.keys())
plt.show()


问:
Sharing login and password for personal project with osCommerce store
I'm integrating an application with the osCommerce shopping cart and want users to be able to log into the app with the same account details they do with osCommerce.

Everything works fine but I got stuck on the user login system. I need to know how to check against a user entered password in my application against the osCommerce user's credentials. They're using a combination of MD5 and salt for generating the password.

How can I use that method to check my user's password?

答:
To check against the password saved in osCommerce, just use the osCommerce function that checks the attempt against the one stored in the database. You'll find this function in the following:

catalog/includes/functions/password_funcs.php

```<code>////
// This funstion validates a plain text password with an encrpyted password
function tep_validate_password($plain, $encrypted) {
  if (tep_not_null($plain) && tep_not_null($encrypted)) {
    // split apart the hash / salt
    $stack = explode(':', $encrypted);

    if (sizeof($stack) != 2) return false;

    if (md5($stack[1] . $plain) == $stack[0]) {
      return true;
    }
  }
  return false;
}
</code>```

So all you need to do is extract the password column from the customers table, based on their entered email address, and compare.

```<code>tep_validate_password(password_attempt, password_from_osC)
</code>```

If you're just going to include it, make sure you also include the catalog/includes/functions/general.php file since that's where the tep_not_null function is defined.

Body:
To check against the password saved in osCommerce, just use the osCommerce function that checks the attempt against the one stored in the database. You'll find this function in the following:

catalog/includes/functions/password_funcs.php

////
// This funstion validates a plain text password with an encrpyted password
function tep_validate_password($plain, $encrypted) {
  if (tep_not_null($plain) && tep_not_null($encrypted)) {
    // split apart the hash / salt
    $stack = explode(':', $encrypted);

    if (sizeof($stack) != 2) return false;

    if (md5($stack[1] . $plain) == $stack[0]) {
      return true;
    }
  }
  return false;
}

So all you need to do is extract the password column from the customers table, based on their entered email address, and compare.

tep_validate_password(password_attempt, password_from_osC)

If you're just going to include it, make sure you also include the catalog/includes/functions/general.php file since that's where the tep_not_null function is defined.


问:
How to install and run electrum wallet with Python3 on server?
I'm implementing bitcoin wallet for the first time, so i don't have much knowledge on this thing.

But by following electrum official documentation , i have tried to install electrum on my macbook and it worked well, now i want to install same on my server running centOS. but installation command python3 run_electrum throws this error

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
  This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted (core dumped)

Is there anything i'm missing here, i'm using python 3.6.4

答:
Also you can use AppImage from official website. Download it in some place of your server and run without installation:  </p>

```<code>$ chmod +x electrum-3.3.8-x86_64.AppImage  # make it executable at first
$ ./electrum-3.3.8-x86_64.AppImage daemon start
</code>```

Body:
Also you can use AppImage from official website. Download it in some place of your server and run without installation:

$ chmod +x electrum-3.3.8-x86_64.AppImage  # make it executable at first
$ ./electrum-3.3.8-x86_64.AppImage daemon start


问:
Flask POST request form data without refreshing page
I am building a small web application that allows the user to enter a transaction through a couple form input fields (such as date, transaction amount, description, etc.). Each time the user clicks a "submit" button a new table row will be created with one column for each input field. In addition to building this table, I want the input data to be sent to my Flask app.

The problem I have is that when the user clicks "submit", the page refreshes and all the table rows are gone. The solution I tried for this is to just have a <button type="button"></button> tag with an id, and when the user clicks it my Javascript code adds a table row without refreshing the page. However, this doesn't work because it doesn't send the data to my Flask app. I also tried using sessionStorage.setItem in Javascript but I don't know how to make that work with my specific code, as the user could click the button 3 times for 3 different transactions and each time the page would refresh.

So my question is, how can I create and display the table rows on the page while ALSO sending the form input data to my Flask app?

For simplification, I have only included 2 input fields here, but there are 8.

HTML:

```<code><form method="POST">
  <div class="list-group-item">
    <label>Date</label>
    <input class="form-control" id="datepicker" type="text" name=expDate value="">
  </div>
  <div class="list-group-item">
    <label>Amount Withdrawn</label>
    <input class="form-control" id="withAmount" type="text" name=expAmountWith value="">
  </div>
  <button id="submit-btn" type="submit" class="btn btn-light submit-btn">Submit</button>
</form>
</code>```

Javascript:

```<code>d3.selectAll('#submit-btn').on('click', buildTable);

function buildTable() {
    var dateInput = d3.select('#datepicker').property('value');
    var withAmount = d3.select('#withAmount').property('value');

    var tableArray = []
    tableArray.push(dateInput, withAmount)

    var row = d3.select('tbody').append('tr');

    tableArray.forEach(function(x) {

        var cell = row.append('td');
        cell.text(x);
    });

};
</code>```

Python:

```<code>app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def record_transaction():

    form = request.form

    if request.method == 'POST':
        expDate = request.form['expDate']
        expAmountWith = request.form['expAmountWith']

    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
So in order to do that, you'll need to use an ajax request

```<code>d3.selectAll('#submit-btn').on('click', buildTable);
$.post( "/your-url", function( data ) { // data is the variable that the URL returns (that means you can't return render_template you have to return some raw data e.g string, json, int, etc)
     buildTable.append(data);
  });
</code>```

I don't know exactly what you need to append so I improvised. What you need to do is to append whatever you sent in data to your table it seems like you know how to do it in JQuery already. I'd suggest that data will be JSON or a list. For more information on how to use the ajax post request visit the documentary

Body:
I am building a small web application that allows the user to enter a transaction through a couple form input fields (such as date, transaction amount, description, etc.). Each time the user clicks a "submit" button a new table row will be created with one column for each input field. In addition to building this table, I want the input data to be sent to my Flask app.

The problem I have is that when the user clicks "submit", the page refreshes and all the table rows are gone. The solution I tried for this is to just have a <button type="button"></button> tag with an id, and when the user clicks it my Javascript code adds a table row without refreshing the page. However, this doesn't work because it doesn't send the data to my Flask app. I also tried using sessionStorage.setItem in Javascript but I don't know how to make that work with my specific code, as the user could click the button 3 times for 3 different transactions and each time the page would refresh.

So my question is, how can I create and display the table rows on the page while ALSO sending the form input data to my Flask app?

For simplification, I have only included 2 input fields here, but there are 8.

HTML:

<form method="POST">

    Date
    <input class="form-control" id="datepicker" type="text" name=expDate value="">

    Amount Withdrawn
    <input class="form-control" id="withAmount" type="text" name=expAmountWith value="">

  <button id="submit-btn" type="submit" class="btn btn-light submit-btn">Submit</button>
</form>

Javascript:

d3.selectAll('#submit-btn').on('click', buildTable);

function buildTable() {
    var dateInput = d3.select('#datepicker').property('value');
    var withAmount = d3.select('#withAmount').property('value');

    var tableArray = []
    tableArray.push(dateInput, withAmount)

    var row = d3.select('tbody').append('tr');

    tableArray.forEach(function(x) {

        var cell = row.append('td');
        cell.text(x);
    });

};

Python:

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def record_transaction():

    form = request.form

    if request.method == 'POST':
        expDate = request.form['expDate']
        expAmountWith = request.form['expAmountWith']

    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

Body:
So in order to do that, you'll need to use an ajax request

d3.selectAll('#submit-btn').on('click', buildTable);
$.post( "/your-url", function( data ) { // data is the variable that the URL returns (that means you can't return render_template you have to return some raw data e.g string, json, int, etc)
     buildTable.append(data);
  });

I don't know exactly what you need to append so I improvised. What you need to do is to append whatever you sent in data to your table it seems like you know how to do it in JQuery already. I'd suggest that data will be JSON or a list. For more information on how to use the ajax post request visit the documentary


答:
Using different merge methods, came to the same answer. Eventually used merge_as0f direction =backward as per your request. Unfortunately not similar to yours in the sense that I have no NaN. Happy to help furtherif you gave information on how you end up with NaN in one row.

```<code>    #Join dateto time and coerce to datetime
    df1['datetime']=pd.to_datetime(df1.date.str.cat(df1.time_1,sep=' '))
    df2['datetime']=pd.to_datetime(df2.date.str.cat(df2.time_2,sep=' '))
    df2['time_2'] = df2['time_2'].apply(lambda x: (x[-5:]))#StripHours from time_2. I anticipate to use it as duration
    #sort to allow merge_asof
    df1=df1.sort_values('datetime')
    df2=df2.sort_values('datetime')
    #Merge to the dataframes joining using datetime to the nearest hour
    df3=pd.merge_asof(df2, df1,on='datetime', by='id', tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward').dropna()
    #df3=df2.merge(df1, left_on=df2.datetime.dt.hour, right_on=df1.datetime.dt.hour, how='left').drop(columns=['key_0', 'id_y', 'date_y']).fillna(0)#Alternative merge
    df3.set_index('datetime', inplace=True)#set datetime as index
    df3['minutes']=df3.index.minute#Extract minute in each row. Looks to me you want the highest minute in each hour
    #Groupby hour idxmax Helps boolean select the index with the highest minutes in an hour. aND DROP UNWANTED ROWS
    finalResult=df3.loc[df3.groupby([df3.index.hour, df3.date_x])['minutes'].idxmax()].reset_index().drop(columns=['datetime','time_1','date_y','minutes'])
   finalResult.columns=['id','date','Duration(min)']
</code>```

finalResult

Title: Conditionally merging dataframes on time variable

Body:
I have to dataframe that I want to merge on the date, id and time variable in order to compute a duration.

from numpy import *
from pandas import *

df1 = DataFrame({
'id': ['a']*4,
'date': ['02-02-2015']*4,
'time_1': ['08:00:00', '09:00:00', '10:30:00', '12:45']})

df1
   id   date         time
0   a   02-02-2015  08:00:00
1   a   02-02-2015  09:00:00
2   a   02-02-2015  10:30:00
3   a   02-02-2015  12:45:00

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

df2 = DataFrame({
'id': ['a']*7,
'date': ['02-02-2015']*7,
'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38']})

df2
    id  date         time
0   a   02-02-2015  08:00:00
1   a   02-02-2015  08:09:00
2   a   02-02-2015  08:04:01
3   a   02-02-2015  08:52:36
4   a   02-02-2015  09:00:00
5   a   02-02-2015  10:30:00
6   a   02-02-2015  11:23:38

The rule that I want my merge to follow is that each row needs in df2 needs to go with the closest previous time in df1.

The intermediate result would be

intermediateResult = DataFrame({
'id': ['a']*8,
'date': ['02-02-2015']*8,
'time_1': ['08:00:00', '08:00:00', '08:00:00','08:00:00', '09:00:00', '10:30:00', '10:30:00', '12:45'],
'time_2': ['08:00:00', '08:09:00', '08:04:01','08:52:36', '09:34:25', '10:30:00', '11:23:38', nan] })

intermediateResult
    id  date        time_1      time_2
0   a   02-02-2015  08:00:00    08:00:00
1   a   02-02-2015  08:00:00    08:09:00
2   a   02-02-2015  08:00:00    08:04:01
3   a   02-02-2015  08:00:00    08:52:36   # end
4   a   02-02-2015  09:00:00    09:34:25   # end
5   a   02-02-2015  10:30:00    10:30:00
6   a   02-02-2015  10:30:00    11:23:38   # end
7   a   02-02-2015  12:45           NaN

Finally, I want to get the time difference between the latest time_2 of each period (inicated with the comment # end) and their corresponding time_1.

The final result would look like this

finalResult = DataFrame({
'id': ['a']*4,
'date': ['02-02-2015']*4,
'Duration': ['00:52:36', '00:34:25', '00:53:38', nan]})

finalResult
    id  date        Duration
0   a   02-02-2015  00:52:36
1   a   02-02-2015  00:34:25
2   a   02-02-2015  00:53:38
3   a   02-02-2015  NaN

Body:
Using different merge methods, came to the same answer. Eventually used merge_as0f direction =backward as per your request. Unfortunately not similar to yours in the sense that I have no NaN. Happy to help furtherif you gave information on how you end up with NaN in one row.

    #Join dateto time and coerce to datetime
    df1['datetime']=pd.to_datetime(df1.date.str.cat(df1.time_1,sep=' '))
    df2['datetime']=pd.to_datetime(df2.date.str.cat(df2.time_2,sep=' '))
    df2['time_2'] = df2['time_2'].apply(lambda x: (x[-5:]))#StripHours from time_2. I anticipate to use it as duration
    #sort to allow merge_asof
    df1=df1.sort_values('datetime')
    df2=df2.sort_values('datetime')
    #Merge to the dataframes joining using datetime to the nearest hour
    df3=pd.merge_asof(df2, df1,on='datetime', by='id', tolerance=pd.Timedelta('2H'),allow_exact_matches=True,direction='backward').dropna()
    #df3=df2.merge(df1, left_on=df2.datetime.dt.hour, right_on=df1.datetime.dt.hour, how='left').drop(columns=['key_0', 'id_y', 'date_y']).fillna(0)#Alternative merge
    df3.set_index('datetime', inplace=True)#set datetime as index
    df3['minutes']=df3.index.minute#Extract minute in each row. Looks to me you want the highest minute in each hour
    #Groupby hour idxmax Helps boolean select the index with the highest minutes in an hour. aND DROP UNWANTED ROWS
    finalResult=df3.loc[df3.groupby([df3.index.hour, df3.date_x])['minutes'].idxmax()].reset_index().drop(columns=['datetime','time_1','date_y','minutes'])
   finalResult.columns=['id','date','Duration(min)']

finalResult


问:
Matrix3d dinamic on scroll

import React, { useState, useRef } from "react";
import { render } from "react-dom";
import styled from "styled-components";
import { useScrollData } from "scroll-data-hook";

const Menu = () => {
  const ref = useRef('myRef');
  const datas = ["Sao Paulo", "New-York", "Lisbonne", "Milan", "Paris"];
  const { direction } = useScrollData({
    onScrollEnd: () => {
      if (ref.current){
        Array.from(ref.current.children).forEach(el => {
        el.style.transform = `translate3d(0,0,0)`;
        el.style.transition = "transform 1s";
        })
      }
    }
  })

  const setTransformMatrix3d = ( matrix3d ) => {
    if (ref.current){
      Array.from(ref.current.children).forEach(el => {
        el.style.transition = "transform 1s";
        el.style.transform = matrix3d;
      })
    }
  };

  if (direction.y) {
    console.log(direction.y);
    let matrix =
      direction.y === "up"
        ? `matrix3d(1,0.09,0,0,0,1.1,0,0,0,0,1,0,0,0,0,1)`
        : `matrix3d(1,-0.09,0,0,0,1.1,0,0,0,0,1,0,0,0,0,1)`;
    setTransformMatrix3d({ matrix });
  }

  return (
    <Wrapper>

        {datas.map((value, index) => (
          <Item key={index} value={value} />
        ))}

    </Wrapper>
  );
};

export default Menu;

const Item = ( {...props} ) => {
  const [isHover, setIsHover] = useState(false);

  return (

      <Link>
        <ContainerMatrix
          onMouseOver={() => setIsHover(!isHover)}
          onMouseLeave={() => setIsHover(!isHover)}
        >
          <ContainerSpan>

              { props.value }
              <Mask className="mask" isHover={isHover} dataMask={props.value} />

          </ContainerSpan>
        </ContainerMatrix>
      </Link>

  );
};

const Wrapper = styled.section`
  transition: transform 100ms;
  will-change: transform;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;
  width: 100vw;
  height: 140vh;
  margin: auto;
  background-color : black;
`

const Link = styled.a`
  text-decoration: none;
  color: inherit;
  background-color: transparent;
`
const Ul = styled.ul`
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;
`

const ContainerMatrix = styled.div`
  transform: translate3d(0px, 0px, 0px);
  transition: transform 100ms;
  will-change: transform;
`

const Li = styled.li`
  transition: transform 2s;
  list-style: none;
  text-transform: uppercase;
`

const ContainerSpan = styled.span`
  position: relative;
  display: inline-block;
  margin: 0;
  color: hsla(0, 0%, 100%, 0.2);
  text-align: center;
  padding: 0 0.15em;
  line-height: 1.15;
  // background-color : red;
`

const Span = styled.span`
  line-height: 1.15;
  font-size: 8.5675vw;
  display: inline-block;
  transform: scaleY(${props => (props.isHover ? "1.1" : "1")}) translateY(${props => (props.isHover ? "-0.1em" : "0em")});
  transition: transform 1.25s cubic-bezier(0.23, 1, 0.32, 1),
    -webkit-transform 1.25s cubic-bezier(0.23, 1, 0.32, 1);
`

const Mask = styled.span.attrs({
  "aria-hidden": "true"
})`
    transform:  translate3d(0, ${props => (props.isHover ? "0%" : "100%")}, 0);
    display: block;
    overflow: hidden;
    transition: transform 1.5s cubic-bezier(.23,1,.32,1),opacity .75s linear,-webkit-transform 1.5s cubic-bezier(.23,1,.32,1);
    will-change: transform,opacity;
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: block;
    pointer-events: none;

    &::before{
    content: '${props => props.dataMask}';
    transform:  translate3d(0,${props => (props.isHover ? "0%" : "-100%")}, 0);
    color: #fff;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: block;
    pointer-events: none;
    transition: opacity .75s linear,-webkit-transform 1.5s cubic-bezier(.23,1,.32,1);
    transition: transform 1.5s cubic-bezier(.23,1,.32,1),opacity .75s linear;
    will-change: transform,opacity;
}
````

This is my first post on stackoverflow.
I'm working with react and I'm trying to find a (proper) way to reproduce an effect on this page : https://www.rudolfson.com/. I've made the font color reveal but i don't know how reproduce the "wave effect" on the text container with a "transform : matrix3d" property who's bindind on scroll. I'm trying hard since 3 days but i need help ! I think it use scroll velocity but i'm not sure. Thank you very much for your answer and your advice.

答:
Rough patch to make it work.

Putting transforms on every li element makes things a lot more difficult.  A lot easier to just apply it to the outer ul, which I've modified.

You'll need to fill in calculations for height (and replace -200) and the code could be cleaner.  But for the most part it works.  I used the matrix3d that Rudolf uses as the base.

codesandbox demo here: https://codesandbox.io/s/lucid-sky-hg2of

```<code>  const setTransformMatrix3d = matrix => {
    Array.from([ref.current]).map((el, index) => {
      el.style.transition = "transform 1s";
      el.style.transform = matrix;
    });
  };

  if (direction.y) {
    console.log(direction.y);
    let matrix =
      direction.y === "up"
        ? `matrix3d(1, 0.000174533, 0, 0, -0.000174533, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)`
        : `matrix3d(1, 0.000174533, 0, 0, -0.000174533, 1, 0, 0, 0, 0, 1, 0, 0, -200, 0, 1)`;
    setTransformMatrix3d(matrix);
  }

  useEffect(() => {
    window.addEventListener("scroll", setTransformMatrix3d);
    return () => {
      window.removeEventListener("scroll", setTransformMatrix3d);
    };
  }, []);
</code>```

Title: Matrix3d dinamic on scroll

Body:
import React, { useState, useRef } from "react";
import { render } from "react-dom";
import styled from "styled-components";
import { useScrollData } from "scroll-data-hook";

const Menu = () => {
  const ref = useRef('myRef');
  const datas = ["Sao Paulo", "New-York", "Lisbonne", "Milan", "Paris"];
  const { direction } = useScrollData({
    onScrollEnd: () => {
      if (ref.current){
        Array.from(ref.current.children).forEach(el => {
        el.style.transform = `translate3d(0,0,0)`;
        el.style.transition = "transform 1s";
        })
      }
    }
  })

  const setTransformMatrix3d = ( matrix3d ) => {
    if (ref.current){
      Array.from(ref.current.children).forEach(el => {
        el.style.transition = "transform 1s";
        el.style.transform = matrix3d;
      })
    }
  };

  if (direction.y) {
    console.log(direction.y);
    let matrix =
      direction.y === "up"
        ? `matrix3d(1,0.09,0,0,0,1.1,0,0,0,0,1,0,0,0,0,1)`
        : `matrix3d(1,-0.09,0,0,0,1.1,0,0,0,0,1,0,0,0,0,1)`;
    setTransformMatrix3d({ matrix });
  }

  return (
    <Wrapper>

        {datas.map((value, index) => (
          <Item key={index} value={value} />
        ))}

    </Wrapper>
  );
};

export default Menu;

const Item = ( {...props} ) => {
  const [isHover, setIsHover] = useState(false);

  return (

      <Link>
        <ContainerMatrix
          onMouseOver={() => setIsHover(!isHover)}
          onMouseLeave={() => setIsHover(!isHover)}
        >
          <ContainerSpan>

              { props.value }
              <Mask className="mask" isHover={isHover} dataMask={props.value} />

          </ContainerSpan>
        </ContainerMatrix>
      </Link>

  );
};

const Wrapper = styled.section`
  transition: transform 100ms;
  will-change: transform;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;
  width: 100vw;
  height: 140vh;
  margin: auto;
  background-color : black;
`

const Link = styled.a`
  text-decoration: none;
  color: inherit;
  background-color: transparent;
`
const Ul = styled.ul`
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;
`

const ContainerMatrix = styled.div`
  transform: translate3d(0px, 0px, 0px);
  transition: transform 100ms;
  will-change: transform;
`

const Li = styled.li`
  transition: transform 2s;
  list-style: none;
  text-transform: uppercase;
`

const ContainerSpan = styled.span`
  position: relative;
  display: inline-block;
  margin: 0;
  color: hsla(0, 0%, 100%, 0.2);
  text-align: center;
  padding: 0 0.15em;
  line-height: 1.15;
  // background-color : red;
`

const Span = styled.span`
  line-height: 1.15;
  font-size: 8.5675vw;
  display: inline-block;
  transform: scaleY(${props => (props.isHover ? "1.1" : "1")}) translateY(${props => (props.isHover ? "-0.1em" : "0em")});
  transition: transform 1.25s cubic-bezier(0.23, 1, 0.32, 1),
    -webkit-transform 1.25s cubic-bezier(0.23, 1, 0.32, 1);
`

const Mask = styled.span.attrs({
  "aria-hidden": "true"
})`
    transform:  translate3d(0, ${props => (props.isHover ? "0%" : "100%")}, 0);
    display: block;
    overflow: hidden;
    transition: transform 1.5s cubic-bezier(.23,1,.32,1),opacity .75s linear,-webkit-transform 1.5s cubic-bezier(.23,1,.32,1);
    will-change: transform,opacity;
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: block;
    pointer-events: none;

    &::before{
    content: '${props => props.dataMask}';
    transform:  translate3d(0,${props => (props.isHover ? "0%" : "-100%")}, 0);
    color: #fff;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: block;
    pointer-events: none;
    transition: opacity .75s linear,-webkit-transform 1.5s cubic-bezier(.23,1,.32,1);
    transition: transform 1.5s cubic-bezier(.23,1,.32,1),opacity .75s linear;
    will-change: transform,opacity;
}
`

This is my first post on stackoverflow.
I'm working with react and I'm trying to find a (proper) way to reproduce an effect on this page : https://www.rudolfson.com/. I've made the font color reveal but i don't know how reproduce the "wave effect" on the text container with a "transform : matrix3d" property who's bindind on scroll. I'm trying hard since 3 days but i need help ! I think it use scroll velocity but i'm not sure. Thank you very much for your answer and your advice.

Body:
Rough patch to make it work.

Putting transforms on every li element makes things a lot more difficult.  A lot easier to just apply it to the outer ul, which I've modified.

You'll need to fill in calculations for height (and replace -200) and the code could be cleaner.  But for the most part it works.  I used the matrix3d that Rudolf uses as the base.

codesandbox demo here: https://codesandbox.io/s/lucid-sky-hg2of

  const setTransformMatrix3d = matrix => {
    Array.from([ref.current]).map((el, index) => {
      el.style.transition = "transform 1s";
      el.style.transform = matrix;
    });
  };

  if (direction.y) {
    console.log(direction.y);
    let matrix =
      direction.y === "up"
        ? `matrix3d(1, 0.000174533, 0, 0, -0.000174533, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)`
        : `matrix3d(1, 0.000174533, 0, 0, -0.000174533, 1, 0, 0, 0, 0, 1, 0, 0, -200, 0, 1)`;
    setTransformMatrix3d(matrix);
  }

  useEffect(() => {
    window.addEventListener("scroll", setTransformMatrix3d);
    return () => {
      window.removeEventListener("scroll", setTransformMatrix3d);
    };
  }, []);


问:
Inconsistency of default sort, pagination parameters name and logic in React Admin
I have a simple front react-admin app, with a Flask API, and I'm trying to implement sort, filter and pagination in my API.

I'm using the dataprovider ra-data-json-server, and according to this spec, I have to implement it with "_sort", "_start", and "_end" parameters (with the underscores).

However, when I look at the GET query performed by my Front app, a sort and pagination will be something like:

```<code>https://balbla.com/#/users?filter=%7B%7D&order=ASC&page=1&perPage=10&sort=roles
</code>```

which is consistent with the doc there https://marmelab.com/react-admin/DataProviders.html

So I'm troubled because:

parameters names are different (the underscore)

the pagination logic is quite different (end and start vs page number and page length).

Did I miss something or is there indeed an inconsistency? Which one to implement? For me, the easiest is to adapt my backend to the actual Front query format, but that's not the doc.

Thx

答:
I also at first had the same confusion as you did, then I came across the source code for ra-data-json-server. It implements the _sort, _order, _start & _end. First of all, you need to have implemented sorting and paging in your API. I will advise you to use this ra-data-json-server Data Provider below:</p>

```<code>import { stringify } from "query-string";
import { fetchUtils } from "ra-core";
/**
 * Maps react-admin que`enter code here`ries to a json-server powered REST API
 *
 * @see https://github.com/typicode/json-server
 *
 * @example
 *
 * getList          => GET http://my.api.url/posts?_sort=title&_order=ASC&_start=0&_end=24
 * getOne           => GET http://my.api.url/posts/123
 * getManyReference => GET http://my.api.url/posts?author_id=345
 * getMany          => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789
 * create           => POST http://my.api.url/posts/123
 * update           => PUT http://my.api.url/posts/123
 * updateMany       => PUT http://my.api.url/posts/123, PUT http://my.api.url/posts/456, PUT http://my.api.url/posts/789
 * delete           => DELETE http://my.api.url/posts/123
 *
 * @example
 *
 * import React from 'react';
 * import { Admin, Resource } from 'react-admin';
 * import jsonServerProvider from 'ra-data-json-server';
 *
 * import { PostList } from './posts';
 *
 * const App = () => (
 *     <Admin dataProvider={jsonServerProvider('http://jsonplaceholder.typicode.com')}>
 *         <Resource name="posts" list={PostList} />
 *     </Admin>
 * );
 *
 * export default App;
 */
var __assign =
  (this && this.__assign) ||
  function () {
    __assign =
      Object.assign ||
      function (t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
      };
    return __assign.apply(this, arguments);
  };

export default (function (apiUrl, httpClient) {
  if (httpClient === void 0) {
    httpClient = fetchUtils.fetchJson;
  }
  return {
    getList: function (resource, params) {
      var _a = params.pagination,
        page = _a.page,
        perPage = _a.perPage;
      var _b = params.sort,
        field = _b.field,
        order = _b.order;
      var query = __assign(
        __assign({}, fetchUtils.flattenObject(params.filter)),
        {
          _sort: field,
          _order: order,
          _start: (page - 1) * perPage + 1,
          _end: page * perPage,
        }
      );
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var headers = _a.headers,
          json = _a.json;
        if (!headers.has("x-total-count")) {
          throw new Error(
            "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?"
          );
        }
        return {
          data: json,
          total: parseInt(headers.get("x-total-count").split("/").pop(), 10),
        };
      });
    },
    getOne: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id).then(
        function (_a) {
          var json = _a.json;
          return {
            data: json,
          };
        }
      );
    },
    getMany: function (resource, params) {
      var query = {
        id: params.ids,
      };
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    getManyReference: function (resource, params) {
      var _a;
      var _b = params.pagination,
        page = _b.page,
        perPage = _b.perPage;
      var _c = params.sort,
        field = _c.field,
        order = _c.order;
      var query = __assign(
        __assign({}, fetchUtils.flattenObject(params.filter)),
        ((_a = {}),
        (_a[params.target] = params.id),
        (_a._sort = field),
        (_a._order = order),
        (_a._start = (page - 1) * perPage),
        (_a._end = page * perPage),
        _a)
      );
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var headers = _a.headers,
          json = _a.json;
        if (!headers.has("x-total-count")) {
          throw new Error(
            "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?"
          );
        }
        return {
          data: json,
          total: parseInt(headers.get("x-total-count").split("/").pop(), 10),
        };
      });
    },
    update: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id, {
        method: "PUT",
        body: JSON.stringify(params.data),
      }).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    // json-server doesn't handle filters on UPDATE route, so we fallback to calling UPDATE n times instead
    updateMany: function (resource, params) {
      return Promise.all(
        params.ids.map(function (id) {
          return httpClient(apiUrl + "/" + resource + "/" + id, {
            method: "PUT",
            body: JSON.stringify(params.data),
          });
        })
      ).then(function (responses) {
        return {
          data: responses.map(function (_a) {
            var json = _a.json;
            return json.id;
          }),
        };
      });
    },
    create: function (resource, params) {
      return httpClient(apiUrl + "/" + resource, {
        method: "POST",
        body: JSON.stringify(params.data),
      }).then(function (_a) {
        var json = _a.json;
        return {
          data: __assign(__assign({}, params.data), { id: json.id }),
        };
      });
    },
    delete: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id, {
        method: "DELETE",
      }).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    // json-server doesn't handle filters on DELETE route, so we fallback to calling DELETE n times instead
    deleteMany: function (resource, params) {
      return Promise.all(
        params.ids.map(function (id) {
          return httpClient(apiUrl + "/" + resource + "/" + id, {
            method: "DELETE",
          });
        })
      ).then(function (responses) {
        return {
          data: responses.map(function (_a) {
            var json = _a.json;
            return json.id;
          }),
        };
      });
    },
  };
});
</code>```

Body:
I have a simple front react-admin app, with a Flask API, and I'm trying to implement sort, filter and pagination in my API.

I'm using the dataprovider ra-data-json-server, and according to this spec, I have to implement it with "_sort", "_start", and "_end" parameters (with the underscores).

However, when I look at the GET query performed by my Front app, a sort and pagination will be something like:

https://balbla.com/#/users?filter=%7B%7D&order=ASC&page=1&perPage=10&sort=roles

which is consistent with the doc there https://marmelab.com/react-admin/DataProviders.html

So I'm troubled because:

parameters names are different (the underscore)

the pagination logic is quite different (end and start vs page number and page length).

Did I miss something or is there indeed an inconsistency? Which one to implement? For me, the easiest is to adapt my backend to the actual Front query format, but that's not the doc.

Thx

Body:
I also at first had the same confusion as you did, then I came across the source code for ra-data-json-server. It implements the _sort, _order, _start & _end. First of all, you need to have implemented sorting and paging in your API. I will advise you to use this ra-data-json-server Data Provider below:

import { stringify } from "query-string";
import { fetchUtils } from "ra-core";
/**
 * Maps react-admin que`enter code here`ries to a json-server powered REST API
 *
 * @see https://github.com/typicode/json-server
 *
 * @example
 *
 * getList          => GET http://my.api.url/posts?_sort=title&_order=ASC&_start=0&_end=24
 * getOne           => GET http://my.api.url/posts/123
 * getManyReference => GET http://my.api.url/posts?author_id=345
 * getMany          => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789
 * create           => POST http://my.api.url/posts/123
 * update           => PUT http://my.api.url/posts/123
 * updateMany       => PUT http://my.api.url/posts/123, PUT http://my.api.url/posts/456, PUT http://my.api.url/posts/789
 * delete           => DELETE http://my.api.url/posts/123
 *
 * @example
 *
 * import React from 'react';
 * import { Admin, Resource } from 'react-admin';
 * import jsonServerProvider from 'ra-data-json-server';
 *
 * import { PostList } from './posts';
 *
 * const App = () => (
 *     <Admin dataProvider={jsonServerProvider('http://jsonplaceholder.typicode.com')}>
 *         <Resource name="posts" list={PostList} />
 *     </Admin>
 * );
 *
 * export default App;
 */
var __assign =
  (this && this.__assign) ||
  function () {
    __assign =
      Object.assign ||
      function (t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
      };
    return __assign.apply(this, arguments);
  };

export default (function (apiUrl, httpClient) {
  if (httpClient === void 0) {
    httpClient = fetchUtils.fetchJson;
  }
  return {
    getList: function (resource, params) {
      var _a = params.pagination,
        page = _a.page,
        perPage = _a.perPage;
      var _b = params.sort,
        field = _b.field,
        order = _b.order;
      var query = __assign(
        __assign({}, fetchUtils.flattenObject(params.filter)),
        {
          _sort: field,
          _order: order,
          _start: (page - 1) * perPage + 1,
          _end: page * perPage,
        }
      );
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var headers = _a.headers,
          json = _a.json;
        if (!headers.has("x-total-count")) {
          throw new Error(
            "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?"
          );
        }
        return {
          data: json,
          total: parseInt(headers.get("x-total-count").split("/").pop(), 10),
        };
      });
    },
    getOne: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id).then(
        function (_a) {
          var json = _a.json;
          return {
            data: json,
          };
        }
      );
    },
    getMany: function (resource, params) {
      var query = {
        id: params.ids,
      };
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    getManyReference: function (resource, params) {
      var _a;
      var _b = params.pagination,
        page = _b.page,
        perPage = _b.perPage;
      var _c = params.sort,
        field = _c.field,
        order = _c.order;
      var query = __assign(
        __assign({}, fetchUtils.flattenObject(params.filter)),
        ((_a = {}),
        (_a[params.target] = params.id),
        (_a._sort = field),
        (_a._order = order),
        (_a._start = (page - 1) * perPage),
        (_a._end = page * perPage),
        _a)
      );
      var url = apiUrl + "/" + resource + "?" + stringify(query);
      return httpClient(url).then(function (_a) {
        var headers = _a.headers,
          json = _a.json;
        if (!headers.has("x-total-count")) {
          throw new Error(
            "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?"
          );
        }
        return {
          data: json,
          total: parseInt(headers.get("x-total-count").split("/").pop(), 10),
        };
      });
    },
    update: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id, {
        method: "PUT",
        body: JSON.stringify(params.data),
      }).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    // json-server doesn't handle filters on UPDATE route, so we fallback to calling UPDATE n times instead
    updateMany: function (resource, params) {
      return Promise.all(
        params.ids.map(function (id) {
          return httpClient(apiUrl + "/" + resource + "/" + id, {
            method: "PUT",
            body: JSON.stringify(params.data),
          });
        })
      ).then(function (responses) {
        return {
          data: responses.map(function (_a) {
            var json = _a.json;
            return json.id;
          }),
        };
      });
    },
    create: function (resource, params) {
      return httpClient(apiUrl + "/" + resource, {
        method: "POST",
        body: JSON.stringify(params.data),
      }).then(function (_a) {
        var json = _a.json;
        return {
          data: __assign(__assign({}, params.data), { id: json.id }),
        };
      });
    },
    delete: function (resource, params) {
      return httpClient(apiUrl + "/" + resource + "/" + params.id, {
        method: "DELETE",
      }).then(function (_a) {
        var json = _a.json;
        return { data: json };
      });
    },
    // json-server doesn't handle filters on DELETE route, so we fallback to calling DELETE n times instead
    deleteMany: function (resource, params) {
      return Promise.all(
        params.ids.map(function (id) {
          return httpClient(apiUrl + "/" + resource + "/" + id, {
            method: "DELETE",
          });
        })
      ).then(function (responses) {
        return {
          data: responses.map(function (_a) {
            var json = _a.json;
            return json.id;
          }),
        };
      });
    },
  };
});


问:
Select average of a column
I have a table named tblPurchaseSub. In this table I have the columns Barcode that can be in several lines, ItemName, PPriceID. I want to get the Barcode, ItemName and the average price of PPriceID column.

```<code>Barcode | ItemName  | PPriceID
----------------------------
2323      Item 1      12
2424      Item 2      14
2121      Item 3      15
2323      Item 1      11
2323      Item 1      13
2424      Item 2      15
</code>```

I have tried: Select Barcode, ItemName, AVG(PPriceID) from tblPurchaseSub group by BarCode

but it seems this is not the correct way to do it.

答:
In standard SQL, every column in the SELECT clause that is not within an aggregate function (such as AVG()) must appear in the GROUP BY clause.

So to make your code a valid aggregation query, you need to add column ItemName to the group by clause:

```<code>select Barcode, ItemName, AVG(PPriceID) avgPPriceID
from tblPurchaseSub
group by BarCode, ItemName
</code>```

This gives you one row per (Barcode, ItemName) tuple, along with the average PPriceID of the corresponding rows in the original table.

Title: Select average of a column

Body:
I have a table named tblPurchaseSub. In this table I have the columns Barcode that can be in several lines, ItemName, PPriceID. I want to get the Barcode, ItemName and the average price of PPriceID column.

Barcode | ItemName  | PPriceID
----------------------------
2323      Item 1      12
2424      Item 2      14
2121      Item 3      15
2323      Item 1      11
2323      Item 1      13
2424      Item 2      15

I have tried: Select Barcode, ItemName, AVG(PPriceID) from tblPurchaseSub group by BarCode

but it seems this is not the correct way to do it.

Body:
In standard SQL, every column in the SELECT clause that is not within an aggregate function (such as AVG()) must appear in the GROUP BY clause.

So to make your code a valid aggregation query, you need to add column ItemName to the group by clause:

select Barcode, ItemName, AVG(PPriceID) avgPPriceID
from tblPurchaseSub
group by BarCode, ItemName

This gives you one row per (Barcode, ItemName) tuple, along with the average PPriceID of the corresponding rows in the original table.


问:
Statement stmt problems netbeans
I'am working on this source code :

```<code>public class AuthentificationClient extends javax.swing.JFrame {

  connexion maconn;
  Statement stmt1;

    public AuthentificationClient() {
        initComponents();
    }

    private void numcompteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Bienvenue ret = new  Bienvenue  () ;
        ret.setVisible(true);
        this.dispose();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String requete ="Select * from Compte where numcompte='"+numcompte.getText()+"' and codec = '"+Arrays.toString(code.getPassword())+"'";
        try {
            Statement stmt1 = maconn.Obtenirconnexion().createStatement();
            ResultSet rs= stmt1.executeQuery(requete);
        } catch (SQLException ex) {
            Logger.getLogger(AuthentificationPharmacien.class.getName()).log(Level.SEVERE, null, ex);
        }
        OpClient oc = new  OpClient  () ;
        oc.setVisible(true);
        this.dispose();
    }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AuthentificationClient().setVisible(true);
            }
        });
    }
</code>```

There is no error but when I execute, it doesn't work correctly! This is the error message that I receive :

答: The variable maconn is never assigned, at least in the code you have provided, so you may be calling a method on a null object.

Title: Statement stmt problems netbeans

Body:
I'am working on this source code :

public class AuthentificationClient extends javax.swing.JFrame {

  connexion maconn;
  Statement stmt1;

    public AuthentificationClient() {
        initComponents();
    }

    private void numcompteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        Bienvenue ret = new  Bienvenue  () ;
        ret.setVisible(true);
        this.dispose();
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String requete ="Select * from Compte where numcompte='"+numcompte.getText()+"' and codec = '"+Arrays.toString(code.getPassword())+"'";
        try {
            Statement stmt1 = maconn.Obtenirconnexion().createStatement();
            ResultSet rs= stmt1.executeQuery(requete);
        } catch (SQLException ex) {
            Logger.getLogger(AuthentificationPharmacien.class.getName()).log(Level.SEVERE, null, ex);
        }
        OpClient oc = new  OpClient  () ;
        oc.setVisible(true);
        this.dispose();
    }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AuthentificationClient().setVisible(true);
            }
        });
    }

There is no error but when I execute, it doesn't work correctly! This is the error message that I receive :


问:
Giving roles in JDA
trying to make a JDA that gives roles on discord, however whenever i use getController() it puts a red line under it and there doesn't seem to be any libraries for ir , how else can i give a role, this is the code : </p>

<pre class="lang-java prettyprint-override"><code>    if(args[0].equalsIgnoreCase(Main.prefix + "mute")){

        if (args.length == 2) {
            Member member = event.getGuild().getMemberById(args[1].replace("<@", "").replace(">", ""));
            Role role = event.getGuild().getRoleById("715670284023365824");

            if (!member.getRoles().contains(role)) {
                //Mute user
                event.getChannel().sendMessage("Muted " + args[1]).queue();
                event.getGuild().getController().addRolesToMember(member, role).complete();
            }
        }
    }
</code>```

答:
You have to use Guild#addRoleToMember:

Guild guild = event.getGuild();
Role role = guild.getRoleById(roleId);
Member member = guild.getMemberById(userId);
guild.addRoleToMember(member, role).queue();
```

Title: Giving roles in JDA

Body:
trying to make a JDA that gives roles on discord, however whenever i use getController() it puts a red line under it and there doesn't seem to be any libraries for ir , how else can i give a role, this is the code :

    if(args[0].equalsIgnoreCase(Main.prefix + "mute")){

        if (args.length == 2) {
            Member member = event.getGuild().getMemberById(args[1].replace("<@", "").replace(">", ""));
            Role role = event.getGuild().getRoleById("715670284023365824");

            if (!member.getRoles().contains(role)) {
                //Mute user
                event.getChannel().sendMessage("Muted " + args[1]).queue();
                event.getGuild().getController().addRolesToMember(member, role).complete();
            }
        }
    }


问:
Cannot get VBA Array to write back to worksheet after making some changes within this project
I have 10 columns from a worksheet ("Player Tracking") that comes out weekly. I am using that tracking sheet to update a master file worksheet("Player Directory"). This code was doing exactly what it was supposed to do but after adding some improvements to the project this part doesnt work. What did I do?

1 What is supposed to happen with the Player Tracking sheet - The Player ID, Name, screen Name, Agent Name, Agent ID, Fee, RB%, Adj RB, Total Hands, and Cash Hands. SrcColumns Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 14).

2 Player Directory is supposed to be compared with the PLayer Tracking to see if there are any updates or additions. The categories are the same but the rows are slightly different. Trgtcolumns Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)

3 If there are additions to be made rows are supposed to be added to insure capacity. The last 6 columns are numbers that should just accumulate. so for example. Fee is 7th columns on player tracking. If that cell had a value of 10 and the weekly report had a value of 2. Id want the existing 10 to be added with the 2 so it would now read 12.

Also I am not getting any error codes but my code might be preventing that too. when I run the code it looks like things are happening. even when i step through it everything looks fine but when the sub ends the directory page is still blank.

```<code>    `Sub DirectoryAdds()
    Const tgtName As String = "Player Directory"
    Const srcFirstRow As Long = 4
    Const tgtFirstRow As Long = 4
    Dim srcColumns As Variant: srcColumns = Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14)
    Dim tgtColumns As Variant: tgtColumns = Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)
    Dim PT As Worksheet: Set PT = PokerBros.Worksheets(Worksheets.Count)
    Dim PD As Worksheet: Set PD = ThisWorkbook.Worksheets(tgtName)
    Dim rng As Range
    Dim Source As Variant, Target As Variant
    Dim NewRow As Long
    Dim Curr As Long
    Dim UB As Long
    Dim i As Long
    Dim k As Long
        If PT Is PD Then MsgBox "Wrong sheet selected.": GoTo exitProcedure
    Set rng = PT.Columns(srcColumns(0)).Find("*", , xlFormulas, , , xlPrevious)
        If rng Is Nothing Then GoTo exitProcedure
        If rng.row < srcFirstRow Then GoTo exitProcedure
        Source = PT.Range(PT.Cells(srcFirstRow, srcColumns(0)), rng)
    Set rng = PD.Columns(tgtColumns(0)).Find("*", , xlFormulas, , , xlPrevious)
        If rng Is Nothing Then GoTo exitProcedure
        If rng.row < tgtFirstRow Then GoTo exitProcedure
        Target = PD.Range(PD.Cells(tgtFirstRow, tgtColumns(0)), rng)
        NewRow = rng.row + 1
        UB = UBound(srcColumns)
        For i = 1 To UBound(Source)
            On Error Resume Next
            Curr = WorksheetFunction.Match(Source(i, 1), Target, 0)
            If Err.Number = 0 Then
                On Error GoTo 0
                GoSub updateExistingRecord
            Else
                On Error GoTo 0
                GoSub addNewRecord
            End If
        Next
        MsgBox "Operation finished successfully."
        GoTo exitProcedure
updateExistingRecord:
    Set rng = PD.Cells(Curr + tgtFirstRow - 1, tgtColumns(UB))
        rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
    Return
addNewRecord:
        For k = 0 To UB - 1
            PD.Cells(NewRow, tgtColumns(k)).Value = _
              PT.Cells(i + srcFirstRow - 1, srcColumns(k)).Value
        Next k
    Set rng = PD.Cells(NewRow, tgtColumns(UB))
        rng.EntireRow.Insert
        rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
        NewRow = NewRow + 1
    Return
exitProcedure:
Erase srcColumns
Erase tgtColumns
updateExistingRecord: Set rng = PD.Cells(Curr + tgtFirstRow - 1, tgtColumns(UB)) rng.Value =
rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value Return addNewRecord: For k = 0 To
UB - 1 PD.Cells(NewRow, tgtColumns(k)).Value = _ PT.Cells(i + srcFirstRow - 1,  srcColumns(k)).Value

Next k Set rng = PD.Cells(NewRow, tgtColumns(UB)) rng.EntireRow.Insert

.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value NewRow = NewRow + 1 Return exitProcedure: Erase srcColumns Erase tgtColumns End Sub`
</code>```

`

答:
Without the goto/gosub

Compiled but not tested.

EDIT: simplified/updated to remove the variant arrays

```<code>Sub DirectoryAdds()

    Const tgtName As String = "Player Directory"
    Const srcFirstRow As Long = 4
    Const tgtFirstRow As Long = 4
    Dim srcColumns As Variant, tgtColumns As Variant
    Dim PT As Worksheet, PD As Worksheet
    Dim rng As Range, rngSource As Range, c As Range
    Dim NewRow As Long, Curr, UB As Long, i As Long, k As Long

    srcColumns = Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14)
    tgtColumns = Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)
    UB = UBound(srcColumns)

    Set PT = PokerBros.Worksheets(Worksheets.Count) 'what is PokerBros?
    Set PD = ThisWorkbook.Worksheets(tgtName)

    If PT Is PD Then
        MsgBox "Wrong sheet selected."
        Exit Sub
    End If

    Set rngSource = PT.Range(PT.Cells(srcFirstRow, srcColumns(0)), _
                             PT.Cells(Rows.Count, srcColumns(0)).End(xlUp))

    For Each c In rngSource.Cells
        If Len(c.Value) > 0 Then
            'Simpler to search full column, but assumes there will be no match
            '  in the header or the cells above it...
            Curr = Application.Match(c.Value, PD.Columns(tgtColumns(0)), 0) 'no Worksheetfunction=no runtime error if no match
            If Not IsError(Curr) Then
                'increment last column
                With PD.Cells(Curr, tgtColumns(UB))
                    .Value = .Value + PT.Cells(c.Row, srcColumns(UB)).Value
                End With
            Else
                'no match: copy over
                Set rng = PD.Cells(Rows.Count, tgtColumns(0)).End(xlUp).Offset(1, 0)
                For k = 0 To UB - 1
                    PD.Cells(rng.Row, tgtColumns(k)).Value = PT.Cells(c.Row, srcColumns(k)).Value
                Next k

                'not sure what the insert is for?
                'rng.EntireRow.Insert
                'rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
            End If 'got a match
        End If     'have a value to search for
    Next c
    MsgBox "Operation finished successfully."

End Sub
</code>```

Body:
I have 10 columns from a worksheet ("Player Tracking") that comes out weekly. I am using that tracking sheet to update a master file worksheet("Player Directory"). This code was doing exactly what it was supposed to do but after adding some improvements to the project this part doesnt work. What did I do?

1 What is supposed to happen with the Player Tracking sheet - The Player ID, Name, screen Name, Agent Name, Agent ID, Fee, RB%, Adj RB, Total Hands, and Cash Hands. SrcColumns Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 14).

2 Player Directory is supposed to be compared with the PLayer Tracking to see if there are any updates or additions. The categories are the same but the rows are slightly different. Trgtcolumns Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)

3 If there are additions to be made rows are supposed to be added to insure capacity. The last 6 columns are numbers that should just accumulate. so for example. Fee is 7th columns on player tracking. If that cell had a value of 10 and the weekly report had a value of 2. Id want the existing 10 to be added with the 2 so it would now read 12.

Also I am not getting any error codes but my code might be preventing that too. when I run the code it looks like things are happening. even when i step through it everything looks fine but when the sub ends the directory page is still blank.

    `Sub DirectoryAdds()
    Const tgtName As String = "Player Directory"
    Const srcFirstRow As Long = 4
    Const tgtFirstRow As Long = 4
    Dim srcColumns As Variant: srcColumns = Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14)
    Dim tgtColumns As Variant: tgtColumns = Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)
    Dim PT As Worksheet: Set PT = PokerBros.Worksheets(Worksheets.Count)
    Dim PD As Worksheet: Set PD = ThisWorkbook.Worksheets(tgtName)
    Dim rng As Range
    Dim Source As Variant, Target As Variant
    Dim NewRow As Long
    Dim Curr As Long
    Dim UB As Long
    Dim i As Long
    Dim k As Long
        If PT Is PD Then MsgBox "Wrong sheet selected.": GoTo exitProcedure
    Set rng = PT.Columns(srcColumns(0)).Find("*", , xlFormulas, , , xlPrevious)
        If rng Is Nothing Then GoTo exitProcedure
        If rng.row < srcFirstRow Then GoTo exitProcedure
        Source = PT.Range(PT.Cells(srcFirstRow, srcColumns(0)), rng)
    Set rng = PD.Columns(tgtColumns(0)).Find("*", , xlFormulas, , , xlPrevious)
        If rng Is Nothing Then GoTo exitProcedure
        If rng.row < tgtFirstRow Then GoTo exitProcedure
        Target = PD.Range(PD.Cells(tgtFirstRow, tgtColumns(0)), rng)
        NewRow = rng.row + 1
        UB = UBound(srcColumns)
        For i = 1 To UBound(Source)
            On Error Resume Next
            Curr = WorksheetFunction.Match(Source(i, 1), Target, 0)
            If Err.Number = 0 Then
                On Error GoTo 0
                GoSub updateExistingRecord
            Else
                On Error GoTo 0
                GoSub addNewRecord
            End If
        Next
        MsgBox "Operation finished successfully."
        GoTo exitProcedure
updateExistingRecord:
    Set rng = PD.Cells(Curr + tgtFirstRow - 1, tgtColumns(UB))
        rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
    Return
addNewRecord:
        For k = 0 To UB - 1
            PD.Cells(NewRow, tgtColumns(k)).Value = _
              PT.Cells(i + srcFirstRow - 1, srcColumns(k)).Value
        Next k
    Set rng = PD.Cells(NewRow, tgtColumns(UB))
        rng.EntireRow.Insert
        rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
        NewRow = NewRow + 1
    Return
exitProcedure:
Erase srcColumns
Erase tgtColumns
updateExistingRecord: Set rng = PD.Cells(Curr + tgtFirstRow - 1, tgtColumns(UB)) rng.Value =
rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value Return addNewRecord: For k = 0 To
UB - 1 PD.Cells(NewRow, tgtColumns(k)).Value = _ PT.Cells(i + srcFirstRow - 1,  srcColumns(k)).Value

Next k Set rng = PD.Cells(NewRow, tgtColumns(UB)) rng.EntireRow.Insert

.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value NewRow = NewRow + 1 Return exitProcedure: Erase srcColumns Erase tgtColumns End Sub`

`

Body:
Without the goto/gosub

Compiled but not tested.

EDIT: simplified/updated to remove the variant arrays

Sub DirectoryAdds()

    Const tgtName As String = "Player Directory"
    Const srcFirstRow As Long = 4
    Const tgtFirstRow As Long = 4
    Dim srcColumns As Variant, tgtColumns As Variant
    Dim PT As Worksheet, PD As Worksheet
    Dim rng As Range, rngSource As Range, c As Range
    Dim NewRow As Long, Curr, UB As Long, i As Long, k As Long

    srcColumns = Array(2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14)
    tgtColumns = Array(2, 3, 4, 10, 11, 13, 12, 14, 15, 16, 17)
    UB = UBound(srcColumns)

    Set PT = PokerBros.Worksheets(Worksheets.Count) 'what is PokerBros?
    Set PD = ThisWorkbook.Worksheets(tgtName)

    If PT Is PD Then
        MsgBox "Wrong sheet selected."
        Exit Sub
    End If

    Set rngSource = PT.Range(PT.Cells(srcFirstRow, srcColumns(0)), _
                             PT.Cells(Rows.Count, srcColumns(0)).End(xlUp))

    For Each c In rngSource.Cells
        If Len(c.Value) > 0 Then
            'Simpler to search full column, but assumes there will be no match
            '  in the header or the cells above it...
            Curr = Application.Match(c.Value, PD.Columns(tgtColumns(0)), 0) 'no Worksheetfunction=no runtime error if no match
            If Not IsError(Curr) Then
                'increment last column
                With PD.Cells(Curr, tgtColumns(UB))
                    .Value = .Value + PT.Cells(c.Row, srcColumns(UB)).Value
                End With
            Else
                'no match: copy over
                Set rng = PD.Cells(Rows.Count, tgtColumns(0)).End(xlUp).Offset(1, 0)
                For k = 0 To UB - 1
                    PD.Cells(rng.Row, tgtColumns(k)).Value = PT.Cells(c.Row, srcColumns(k)).Value
                Next k

                'not sure what the insert is for?
                'rng.EntireRow.Insert
                'rng.Value = rng.Value + PT.Cells(i + srcFirstRow - 1, srcColumns(UB)).Value
            End If 'got a match
        End If     'have a value to search for
    Next c
    MsgBox "Operation finished successfully."

End Sub


问:
Extracting text from an overflowed span tag using BeautifulSoup in Python
I am very new to Python, catching up with a practice exercise.
While doing a text extract from an HTML span tag, some portion was under "Read more" and unless I click it there, the span tag doesn't get updated with the extire text. This means while I am running BeautifulSoup and findAll for the tag and the class, the only first part, without the "read more" section, is returning as an extract. Not able to figure out how I should go after? This is a text mining exercise for hotel reviews.
Code is as below, not providing the full part:

```<code>url_soup=soup(url_html,"html.parser")
profiles = url_soup.findAll("div",{"class":"hotels-community-tab-common-Card__card--ihfZB hotels-community-tab-common-Card__section--4r93H"})
for profile in profiles:
     Review_Body = profile.findAll("q",{"class":"location-review-review-list-parts-ExpandableReview__reviewText--gOmRC"})
     Review_Body = Review_Body[0].text.replace(",","").replace("\r\n","").strip(" ")
</code>```

Page without clicking "read more"
Page after clicking "read more", when the entire text till end is visible

As said, this only returns the part without clicking the "read more" and followed by a "...". PLease help.
PS: I am not installed and using Srapy or Selenium modules. Will they be easier?

答:
I think that the website you are using (not the one you provided but instead: link
is calling different website structures, so unfortunately, i am gonna be of little help. But in case it get you going you could do this and change the code for each iteration (I would be keen to know if there is a better solution).
So again in case it helps:

```<code>
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup as _BS

url_html = "https://www.tripadvisor.com/Profile/HollyABC"

def get_web_request(url_to_open: str):
    my_header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
    request = requests.get(url=url_to_open, headers=my_header)
    return request

web_page = get_web_request(url_to_open=url_html)
my_soup = _BS(web_page.text, "lxml")

container_tag = my_soup.find_all('div', attrs={'id': 'content'})
if len(container_tag) > 1:
    exit('Error with the defined container: too many answers(len shoud be one).')
print('len of container_tag', len(container_tag))

row_tags = container_tag[0].find_all('div', attrs={
    'class': 'social-section-core-CardSection__card_section--33UYa ui_card section'})
print('len of rows_tag', len(row_tags))

if row_tags is None or len(row_tags) == 0:
    exit('No result found in container')

href_url_list = []
for row_tag in row_tags:
    # find trip advisor href
    href_tag = row_tag.find_all('a', href=True)
    href = href_tag[2].get('href')
    href_url = urljoin(url_html, href)
    href_url_list.append(href_url)

print(href_url_list)

for href_url in href_url_list:
    web_page = get_web_request(url_to_open=href_url)
    my_soup = _BS(web_page.text, "lxml")
    # assuming it is always the 1st post box...
    text_tag = my_soup.find('div', attrs={'class':'firstPostBox'})
    body_tag = text_tag.find('div', attrs={'class':'postBody'}).find('p')
    print(body_tag.get_text())

</code>```

So you should get the actual urls to each hotels, but then you would have to handle the soup for each diiferent web structure. I did it for the first one, but doesn't seem to be a great solution to be fair. Hoping it gets the ball rolling with you or the community.
Best

NB:

I use 'lxml' which you would need to pip install, but I assume would work with 'html.parser' (not the problem here).

I don't think Selenium will sort the problem as you will still have different web structures once you click
-One option would be to gather href/url(like I did) but as well the partial text, and then to look for the partial text in the new last url loop. that shold work.

Body:
I am very new to Python, catching up with a practice exercise.
While doing a text extract from an HTML span tag, some portion was under "Read more" and unless I click it there, the span tag doesn't get updated with the extire text. This means while I am running BeautifulSoup and findAll for the tag and the class, the only first part, without the "read more" section, is returning as an extract. Not able to figure out how I should go after? This is a text mining exercise for hotel reviews.
Code is as below, not providing the full part:

url_soup=soup(url_html,"html.parser")
profiles = url_soup.findAll("div",{"class":"hotels-community-tab-common-Card__card--ihfZB hotels-community-tab-common-Card__section--4r93H"})
for profile in profiles:
     Review_Body = profile.findAll("q",{"class":"location-review-review-list-parts-ExpandableReview__reviewText--gOmRC"})
     Review_Body = Review_Body[0].text.replace(",","").replace("\r\n","").strip(" ")

Page without clicking "read more"
Page after clicking "read more", when the entire text till end is visible

As said, this only returns the part without clicking the "read more" and followed by a "...". PLease help.
PS: I am not installed and using Srapy or Selenium modules. Will they be easier?

Body:
I think that the website you are using (not the one you provided but instead: link
is calling different website structures, so unfortunately, i am gonna be of little help. But in case it get you going you could do this and change the code for each iteration (I would be keen to know if there is a better solution).
So again in case it helps:

from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup as _BS

url_html = "https://www.tripadvisor.com/Profile/HollyABC"

def get_web_request(url_to_open: str):
    my_header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
    request = requests.get(url=url_to_open, headers=my_header)
    return request

web_page = get_web_request(url_to_open=url_html)
my_soup = _BS(web_page.text, "lxml")

container_tag = my_soup.find_all('div', attrs={'id': 'content'})
if len(container_tag) > 1:
    exit('Error with the defined container: too many answers(len shoud be one).')
print('len of container_tag', len(container_tag))

row_tags = container_tag[0].find_all('div', attrs={
    'class': 'social-section-core-CardSection__card_section--33UYa ui_card section'})
print('len of rows_tag', len(row_tags))

if row_tags is None or len(row_tags) == 0:
    exit('No result found in container')

href_url_list = []
for row_tag in row_tags:
    # find trip advisor href
    href_tag = row_tag.find_all('a', href=True)
    href = href_tag[2].get('href')
    href_url = urljoin(url_html, href)
    href_url_list.append(href_url)

print(href_url_list)

for href_url in href_url_list:
    web_page = get_web_request(url_to_open=href_url)
    my_soup = _BS(web_page.text, "lxml")
    # assuming it is always the 1st post box...
    text_tag = my_soup.find('div', attrs={'class':'firstPostBox'})
    body_tag = text_tag.find('div', attrs={'class':'postBody'}).find('p')
    print(body_tag.get_text())

So you should get the actual urls to each hotels, but then you would have to handle the soup for each diiferent web structure. I did it for the first one, but doesn't seem to be a great solution to be fair. Hoping it gets the ball rolling with you or the community.
Best

NB:

I use 'lxml' which you would need to pip install, but I assume would work with 'html.parser' (not the problem here).

I don't think Selenium will sort the problem as you will still have different web structures once you click
-One option would be to gather href/url(like I did) but as well the partial text, and then to look for the partial text in the new last url loop. that shold work.


问:
How can I most easily do IPC/RPC between Cocoa (client) and Java (server) running on the same host?
The Java end is a Bukkit plugin, so I don't have the freedom to build on a servlet engine like Tomcat. I don't need arbitrary access to any object; I just want to expose a subset of functionality available to plugins to my wrapper application.

The Cocoa application, I am building from the ground up, so the restrictions are a bit looser. It's a wrapper for the server with limited support for configuring certain plugins.

Something that can communicate over Unix sockets would be ideal since the processes are running on a single host, but TCP sockets are ok too. I'm not really picky. If I end up using TCP then I'll consider adding support for remote management, but it's not a priority. I don't want Unix sockets badly enough to bother with all the hoops I'd have to jump through to use them.

答: You might want to look at zeromq, it has bindings for Objective-C and Java, supports IPC, TCP, and more.</p>


问:
How does the ternary operator in the else statement work in this example?
Though the question is old but still baffles me alot

If you've watched the javascript udemy course...

In the pig game the guy created he said

```<code>If(dice !== 1) {
//Let's assume I've created my roundscore and other variables
}

/*What really baffles me is when he got to else statements he said */

else {
activePlayer === 0? activeplayer = 1 : activeplayer = 0
}

//Please why can't he say

else if (dice === 1){
activeplayer = 1
}

/*Please I need a clear explanations */
</code>```

答:
Ternary operators and if/else statements can be interchangeable and either can be used in the place of others in most cases. In your case, the if statement checks if the dice does not equal one, then goes to the else statement. In here the code checks if the activePlayer variable is equal to zero: if it is, then the variable is set to 1 and if not the variable is set to 0.

However, there seems to be a mistake in the if statement as when the if condition is satisfied, the code will not regard the else statement, meaning the else statement will only run if the variable = 1, meaning the ternary operator is redundant. Look over your question again and see, I believe there is a mistake in your code or even the video.

Body:
Though the question is old but still baffles me alot

If you've watched the javascript udemy course...

In the pig game the guy created he said

If(dice !== 1) {
//Let's assume I've created my roundscore and other variables
}

/*What really baffles me is when he got to else statements he said */

else {
activePlayer === 0? activeplayer = 1 : activeplayer = 0
}

//Please why can't he say

else if (dice === 1){
activeplayer = 1
}

/*Please I need a clear explanations */