问:
PyObject_CallMethod: call static member function from c++
I've embedded Python (3.6) code into my C++ application successfully. I use the Python/C API to call methods from this library. An overview of the python module is as follows:

class MyClass(object):
    def __init__(args: str) -> None:
        ...
        return

    def callable_method(*args) -> Tuple:
        ...
        return some_tuple

    @staticmethod()
    def create_from_cli_args(argv: List[str]) -> 'MyClass':
        ...
        return MyClass(parsed_args)
```
<p>The static method is a new addition to my code to move exception logic from the <code>__init__</code> function to another function and yield an object. The C++ code to construct an object before was as follows:</p>
<pre class="lang-cpp prettyprint-override"><code>PyObject *module_name = PyUnicode_FromString("module_path.my_class");

// Load the module object
PyObject *module = PyImport_Import(module_name);
if(module == nullptr) return;
Py_DECREF(module_name);

// Get callable list from module
PyObject *dict = PyModule_GetDict(module);
if(dict == nullptr) return;
Py_DECREF(module);

// Builds the name of a callable class
PyObject *my_class = PyDict_GetItemString(dict, "MyClass");
if(python_class == nullptr) return;

// Check if python class is callable
if(!PyCallable_Check(my_class)) return;

// Populate args for class instantiation
PyObject *py_args = PyTuple_New(1);
PyTuple_SetItem(py_args, 0, PyUnicode_FromString("Initialize_Configs"));

// Construct object
PyObject *my_class_obj = PyObject_CallObject(my_class, py_args);
if(my_class_obj == nullptr) return;
</code>```

The above code snippet works, however, with the addition of the static method I'm trying to use to create an object of my_class, I'm unable to figure out how to call a static method of a class. I've tried using PyObject *my_class = PyDict_GetItemString(dict, "MyClass.create_my_class"); as well as PyObject_CallMethod(my_class, "create_my_class", kargs, kwargs) but that doesn't work either. I'd appreciate any help.

答:
As the person in the comments suggested, I was incorrectly calling the static method. The solution is:

...
if(!PyCallable_Check(my_class)) return;

// A static method can be called the same as a normal method in python.
PyObject *my_class_object = PyObject_CallMethod(my_class, "create_from_cli_args", "s", "--cli_args");

if(!my_class_object) return;
```

Body:
I've embedded Python (3.6) code into my C++ application successfully. I use the Python/C API to call methods from this library. An overview of the python module is as follows:

class MyClass(object):
    def __init__(args: str) -> None:
        ...
        return

    def callable_method(*args) -> Tuple:
        ...
        return some_tuple

    @staticmethod()
    def create_from_cli_args(argv: List[str]) -> 'MyClass':
        ...
        return MyClass(parsed_args)

The static method is a new addition to my code to move exception logic from the __init__ function to another function and yield an object. The C++ code to construct an object before was as follows:

PyObject *module_name = PyUnicode_FromString("module_path.my_class");

// Load the module object
PyObject *module = PyImport_Import(module_name);
if(module == nullptr) return;
Py_DECREF(module_name);

// Get callable list from module
PyObject *dict = PyModule_GetDict(module);
if(dict == nullptr) return;
Py_DECREF(module);

// Builds the name of a callable class
PyObject *my_class = PyDict_GetItemString(dict, "MyClass");
if(python_class == nullptr) return;

// Check if python class is callable
if(!PyCallable_Check(my_class)) return;

// Populate args for class instantiation
PyObject *py_args = PyTuple_New(1);
PyTuple_SetItem(py_args, 0, PyUnicode_FromString("Initialize_Configs"));

// Construct object
PyObject *my_class_obj = PyObject_CallObject(my_class, py_args);
if(my_class_obj == nullptr) return;

The above code snippet works, however, with the addition of the static method I'm trying to use to create an object of my_class, I'm unable to figure out how to call a static method of a class. I've tried using PyObject *my_class = PyDict_GetItemString(dict, "MyClass.create_my_class"); as well as PyObject_CallMethod(my_class, "create_my_class", kargs, kwargs) but that doesn't work either. I'd appreciate any help.


来源: stackexchange

问:
Fix: React Native App error: "Task :app:processDebugMainManifest FAILED" with jdk17
I had problems setting up the updated environment for app development with RN.

openjdk version "17.0.1" / node 16+

If you're having the same problem, here's how to solve it:

Error Execution failed for task ':app:processDebugMainManifest'.

答:
For java 16 or 17, just add line in /android/gradle.properties

#Fix bug java 17
org.gradle.jvmargs=--add-opens java.base/java.io=ALL-UNNAMED

ContentLicense: CC BY-SA 4.0


问:
Require One of a Set of Fields in SQL
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

```<code>machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}
</code>```

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?

答:
At least one of these [three] fields is required

You might concatenate the three, first converting null to empty string:

```<code>           CONCAT(   ifnull(host,'') , ifnull(ip,'') , ifnull(tag,'')  )
</code>```

and then this constraint:

```<code>         length(   CONCAT(   ifnull(host,'') , ifnull(ip,'') , ifnull(tag,'')  )  ) > 0
</code>```

if mySQL supported check constraints.

ContentLicense: CC BY-SA 3.0

Title: Require One of a Set of Fields in SQL

Body:
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?

Body:
At least one of these [three] fields is required

You might concatenate the three, first converting null to empty string:

           CONCAT(   ifnull(host,'') , ifnull(ip,'') , ifnull(tag,'')  )

and then this constraint:

         length(   CONCAT(   ifnull(host,'') , ifnull(ip,'') , ifnull(tag,'')  )  ) > 0

if mySQL supported check constraints.


问:
Unrecognized selector sent to instance.. 'NSInvalidArgumentException' for MapView delegate
Swift 4/Google Maps.

The crash I get is..

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[UIView setDelegate:]:
  unrecognized selector sent to instance 0x7fa1eb50d7e0'

Yes, I know there are a lot of threads on this, but looking through them has not helped me.  I have debugged enough where I have a suspect, but do not know exactly how to resolve.

Here's the git repo

Some detail..  The MapViewController has three UIViews.

MapViewController

Main View (default one that comes with the controller)
-- Menu (sub view of Main View)
-- Map (sub view of Main View)

I believe I've narrowed down the crash to the statement

```<code>self.mapView.delegate = self
</code>```

Here's most of the code for the MapViewController.

```<code>import UIKit
import GoogleMaps
import FirebaseDatabase

class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet var mapView: GMSMapView!

    var locationOfInterestMarker = GMSMarker()
    var userMarker = GMSMarker()
    var locationManager = CLLocationManager()
    let zoom:Float = 15
    let locationOfInterestImage:String = "hhouseicon"
    let userMarkerImage:String = "witchicon"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.getLocations()
        self.locationManager.delegate = self
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startMonitoringSignificantLocationChanges()
        /**
                The next line causes crash.  I believe I need to set the delegate to something other than self.  Set the delegate to the View named Map.  However I'm not sure about the actual code for that.
         **/
        self.mapView.delegate = self //Crashes
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        guard status == .authorizedWhenInUse else {
            return
        }
        self.locationManager.startUpdatingLocation()
        self.mapView.isMyLocationEnabled = true
        self.mapView.settings.myLocationButton = true
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else {
            return
        }
        self.locationManager.stopUpdatingLocation()
        self.mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
        self.placeMarker(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, marker: self.userMarker, imageName: userMarkerImage)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if let destination = segue.destination as? LocationDetialViewController {
        destination.coordinate = locationManager.location?.coordinate
        } else {
            return
        }
    } . . .
     func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
            performSegue(withIdentifier: "locationDetailSegue", sender: self)
            return false
        }

    }//MapViewController
</code>```

答: I had a similar issue, but the problem was i didn't inherit the module from target

Body:
Swift 4/Google Maps.

The crash I get is..

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[UIView setDelegate:]:
  unrecognized selector sent to instance 0x7fa1eb50d7e0'

Yes, I know there are a lot of threads on this, but looking through them has not helped me.  I have debugged enough where I have a suspect, but do not know exactly how to resolve.

Here's the git repo

Some detail..  The MapViewController has three UIViews.

MapViewController

Main View (default one that comes with the controller)
-- Menu (sub view of Main View)
-- Map (sub view of Main View)

I believe I've narrowed down the crash to the statement

self.mapView.delegate = self

Here's most of the code for the MapViewController.

import UIKit
import GoogleMaps
import FirebaseDatabase

class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet var mapView: GMSMapView!

    var locationOfInterestMarker = GMSMarker()
    var userMarker = GMSMarker()
    var locationManager = CLLocationManager()
    let zoom:Float = 15
    let locationOfInterestImage:String = "hhouseicon"
    let userMarkerImage:String = "witchicon"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.getLocations()
        self.locationManager.delegate = self
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startMonitoringSignificantLocationChanges()
        /**
                The next line causes crash.  I believe I need to set the delegate to something other than self.  Set the delegate to the View named Map.  However I'm not sure about the actual code for that.
         **/
        self.mapView.delegate = self //Crashes
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        guard status == .authorizedWhenInUse else {
            return
        }
        self.locationManager.startUpdatingLocation()
        self.mapView.isMyLocationEnabled = true
        self.mapView.settings.myLocationButton = true
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else {
            return
        }
        self.locationManager.stopUpdatingLocation()
        self.mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
        self.placeMarker(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, marker: self.userMarker, imageName: userMarkerImage)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if let destination = segue.destination as? LocationDetialViewController {
        destination.coordinate = locationManager.location?.coordinate
        } else {
            return
        }
    } . . .
     func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
            performSegue(withIdentifier: "locationDetailSegue", sender: self)
            return false
        }

    }//MapViewController


问:
I have a find command used in my script. command use - find . -type f -name "*.txt" -mtime +30. How does this command work? Does it consider day alone

find . -type f -name "*.txt" -mtime +30
```

Does this command consider day alone? Or day and time?

If I am executing the command on 12.00 pm, will it fetch files older than 30 days and created before 12 pm?

答:
I don't have unix machine at hand to test, but past experience leads me to believe that hours are not considered and simply cut off.  That means for me that a day therefor starts at 00:00 and lasts until 24:00 (midnight).
Also, -mtime is not creation time, but modify time.

```<code>find
.             (= current directory)
-type f       (= {and} files only)
-name "*.txt" (= {and} all files with .txt extension)
-mtime +30    (= {and} files modified greater than 30 days previously)
</code>```

Executing that command on Jan 31 will return all files that were modified on or before any hour of Jan 1, and match the other criteria.

https://man7.org/linux/man-pages/man1/find.1.html

Body:
find . -type f -name "*.txt" -mtime +30

Does this command consider day alone? Or day and time?

If I am executing the command on 12.00 pm, will it fetch files older than 30 days and created before 12 pm?

Body:
I don't have unix machine at hand to test, but past experience leads me to believe that hours are not considered and simply cut off.  That means for me that a day therefor starts at 00:00 and lasts until 24:00 (midnight).
Also, -mtime is not creation time, but modify time.

find
.             (= current directory)
-type f       (= {and} files only)
-name "*.txt" (= {and} all files with .txt extension)
-mtime +30    (= {and} files modified greater than 30 days previously)

Executing that command on Jan 31 will return all files that were modified on or before any hour of Jan 1, and match the other criteria.

https://man7.org/linux/man-pages/man1/find.1.html


问:
Parameter substitution for a SQLite "IN" clause
I am trying to use parameter substitution with SQLite within Python for an IN clause.  Here is a complete running example that demonstrates:

```<code>import sqlite3

c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')

for name in 'Ubuntu Fedora Puppy DSL SuSE'.split():
  c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] )

desired_ids = ["1", "2", "5", "47"]
result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ())
for result in result_set:
  print result
</code>```

It prints out:

(1, u'Ubuntu')
  (2, u'Fedora')
  (5, u'SuSE')

As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.

When I try:

```<code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ])
</code>```

I get an empty result set, and when I try:

```<code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] )
</code>```

I get:

InterfaceError: Error binding parameter 0 - probably unsupported type.

While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery.  To wit:

```<code>UPDATE dir_x_user SET user_revision = user_attempted_revision
WHERE user_id IN
    (SELECT user_id FROM
        (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN
            ("Argl883", "Manf496", "Mook657") GROUP BY user_id
        )
    )
</code>```

答:
I needed to use some other named parameters so I've developed two helper functions that may be worth sharing.

def prepare_list_query(name, values):
    """Prepare SQLite query with named parameters."""
    list_query = ", ".join(":{}_{}".format(name, i) for i in range(len(values)))
    return list_query

def prepare_list_dict(name, values):
    """Prepare SQLite dict with named parameters."""
    list_dict = {"{}_{}".format(name, i): value for i, value in enumerate(values)}
    return list_dict

# Usage:

desired_ids = ["1", "2", "5", "47"]
desired_types = ["active", "inactive"]

sql = "SELECT * FROM distro WHERE id IN ({}) AND type IN ({})".format(
    prepare_list_query("desired_id", desired_ids),
    prepare_list_query("desired_type", desired_types),
)
sql_dict = {"some": "other parameters you might need"}
sql_dict.update(prepare_list_dict("desired_id", desired_ids))
sql_dict.update(prepare_list_dict("desired_type", desired_types))

# # This results in:
# sql = "SELECT * FROM distro WHERE id IN (:desired_id_0, :desired_id_1, :desired_id_2, :desired_id_3) AND type IN (:desired_type_0, :desired_type_1)

# # and
# sql_dict = {
#     "some": "other parameters you might need",
#     "desired_id_0": "1",
#     "desired_id_1": "2",
#     "desired_id_2": "5",
#     "desired_id_3": "47",
#     "desired_type_0": "active",
#     "desired_type_1": "inactive",
# }

# And now execute the query:
result = c.execute(sql, sql_dict)
```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use parameter substitution with SQLite within Python for an IN clause.  Here is a complete running example that demonstrates:

import sqlite3

c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')

for name in 'Ubuntu Fedora Puppy DSL SuSE'.split():
  c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] )

desired_ids = ["1", "2", "5", "47"]
result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ())
for result in result_set:
  print result

It prints out:

(1, u'Ubuntu')
  (2, u'Fedora')
  (5, u'SuSE')

As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.

When I try:

result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ])

I get an empty result set, and when I try:

result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] )

I get:

InterfaceError: Error binding parameter 0 - probably unsupported type.

While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery.  To wit:

UPDATE dir_x_user SET user_revision = user_attempted_revision
WHERE user_id IN
    (SELECT user_id FROM
        (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN
            ("Argl883", "Manf496", "Mook657") GROUP BY user_id
        )
    )


问:
How to correctly use Locomotive Scroll with Next.js routing?
I'm using locomotive-scroll with Next.js and all working fine. But after route to a different page, my scroll won't destroy and 2 scrolls overlap each other.

How to correctly reinit locomotive-scroll in Next.js after route?

My code example:

```<code>function MyApp({ Component, pageProps }) {
    useEffect(() => {
        import("locomotive-scroll").then((locomotiveModule) => {
            let scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true,
             });

             scroll.destroy();  //<-- DOESN'T WORK OR IDK

             setTimeout(function () {
                 scroll.init();
             }, 400);
         });
     });

     return (
         <main data-scroll-container>
             <Component {...pageProps} />
         </main>
     );
}
</code>```

答:
everything @juliomalves said is true. but i just wanted to add one point.
Locomotive works by initialising itself and reading the actual document size on page load. but the situation with next js routing is that the page loads only once, after that its only components changes, no actual page reloading. so the Scroll instance will assume the page is still the same size on load. this leads to a lot of bugs and page breakage.

the way i solved it is by adding this line at the app component:
useEffect(()=> window.dispatchEvent(new Event('resize')), [Component])

this way the resize event will trigger every time the page "component" is switched. the locomotive Scroll instance will pick up this event and recalculate the page size according to the new component size.

Body:
I'm using locomotive-scroll with Next.js and all working fine. But after route to a different page, my scroll won't destroy and 2 scrolls overlap each other.

How to correctly reinit locomotive-scroll in Next.js after route?

My code example:

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        import("locomotive-scroll").then((locomotiveModule) => {
            let scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true,
             });

             scroll.destroy();  //<-- DOESN'T WORK OR IDK

             setTimeout(function () {
                 scroll.init();
             }, 400);
         });
     });

     return (

             <Component {...pageProps} />

     );
}


问:
Handle webGL particles independently
I created this particle system with scratch webGL code and i would translate the particles emitter you can experiment here :
https://codepen.io/stephanemill/pen/vYWgKNP

By moving particles, I want to new particles run in new direction, but previous stay in their initial direction.

...Like on this render (movment is due to the mouse in this case) : https://ics-creative.github.io/ParticleJS/docs/examples/mouse-tracking.html

Here is my vertex shader code :

```<code>            void main(void) {
                gl_PointSize = size;
                vColor = color;

                // Settings of the particle
                // ---------------------------------
                float modTime   = time / timeFactor;
                float speed     = speed_angle_offset.x;
                float angle     = speed_angle_offset.y;
                float offset    = speed_angle_offset.z;
                float G         = gravity.x;
                float x0        = position.x;
                float y0        = position.y;

                // Calculations for the non-ending particle flow
                // -------------------------------------------------
                float offsetStart   = abs(offset) * lifetime;
                float offsetTime    = clamp(modTime - offsetStart, 0., 2e10);
                offsetTime          = mod(offsetTime, lifetime);

                // Moving emitter... The problem IS HERE
                // -------------------------------------------------
                if(modTime - offsetTime > deltaXYT.z ){
                    x0  = x0 + deltaXYT.x;
                    y0  = y0 + deltaXYT.y;
                }

                // Equations of parabolic shoot to set x and y position
                // -----------------------------------------------------
                float x = speed * cos(angle) * offsetTime + x0;
                float y = -.5 * G * pow(offsetTime, 2.) + speed * sin(angle) * offsetTime + y0;

                // Ratio canvas
                // ---------------------------------
                x /= ratio;

                // Printing particle
                // ---------------------------------
                gl_Position=vec4(x, y, 0, 1.);
            }`;

</code>```

About my code :

The translation on the Y axis is creating line 50 with a setinterval for a slow visualization.

My solution is to create a deltaXYT uniform (line 380) which embedded the X delta, the Y delta, and the exact time (this.time) the delta position is applied to the X,Y position of each particle.

This technique is implemented in the getVertexShader function line 430 (Moving emitter)

As you can see, the result is not that i expect, because each particle doesn't memorize its own deltaXY in order to run its own way... So what you're seeing is a batch of young particles running on the most recent deltaXYT, and a batch of other particles running on the default deltaXYT line 155 (which brings no modification on position attribute)

I suppose i'm not in the right way, so did you have any suggestion to do this thing, which, at the beginning, didn't seem so hard.

答:
Each particle should have a birth time, but also a birth position.
This position will change at every particle reborn and cannot be computed by the vertex shader. Especially if it is a mouse position, for example.
You need to store this new position somewhere.

One solution could be to store it in the attributes:

attribute vec2 attInitialPosition;

attribute vec2 attInitialSpeed;

attribute float attBirthTime;

Then the "reborn" logic can be delegated to Javascript code that will update the attributes once changed.

Of course, sending the whole Data Array for all the 500 particles is not a good idea.
Instead, we can just send what has changed.

To explain the trick in an easy way, let's assume we will create a new particle at each frame. That means that we will create particles at a rate of 60 per seconds if we are lucky.

Then, at first frame, you update the attributes of vertex 1, at frame 2 the attributes of vertex 2, etc...
Of course at frame 501 you update again the attributes of vertex 1 and so on.

With 500 particules, that means that each one will leave for 500 * 16 ms = 8 seconds.

And at each frame, you can update the vertex like this:

```<code>    public pushDataSubArray(data: Float32Array, start: number, end: number) {
        const { gl, vertBuff } = this
        gl.bindBuffer(gl.ARRAY_BUFFER, vertBuff)
        const subData = data.subarray(start * 5, end * 5)
        gl.bufferSubData(
            gl.ARRAY_BUFFER,
            start * Float32Array.BYTES_PER_ELEMENT * 5,
            subData
        )
    }
</code>```

The subarray() method is super cool because it does not copy de data.
It's more like a window on a portion of your initial array.

Of course if you need more control, you will decide how many particles you update per frame depending on the rate and the lifetime you want. But I won't give you an example here because it complexifies the code and make it more difficult to understand.

Here is the vertex shader code:

```<code>uniform float uniTime;

attribute vec2 attInitialPosition;
attribute vec2 attInitialSpeed;
attribute float attBirthTime;

varying vec3 varColor;

const vec2 GRAVITY = vec2(0, -1) * 0.0000005;
const vec3 YELLOW = vec3(1.0, 1.0, 0.1);
const vec3 RED = vec3(0.8, 0.0, 0.0);

void main() {
    float t = uniTime - attBirthTime;
    float t2 = t * t;
    gl_Position = vec4(
        t2 * GRAVITY + t * attInitialSpeed + attInitialPosition,
        0.5, 1.0
    );
    gl_PointSize = 128.0 - 0.02 * t;
    float life = clamp(t * 0.005, 0.0, 1.0);
    float light = 11.0 - 10.0 * life * life;
    varColor = light * mix(YELLOW, RED, life);
}
</code>```

See it in action here (move your mouse on the screen to change the birth location):

https://codepen.io/tolokoban/pen/zYPZJJX?editors=0010

Title: Handle webGL particles independently

Body:
I created this particle system with scratch webGL code and i would translate the particles emitter you can experiment here :
https://codepen.io/stephanemill/pen/vYWgKNP

By moving particles, I want to new particles run in new direction, but previous stay in their initial direction.

...Like on this render (movment is due to the mouse in this case) : https://ics-creative.github.io/ParticleJS/docs/examples/mouse-tracking.html

Here is my vertex shader code :

            void main(void) {
                gl_PointSize = size;
                vColor = color;

                // Settings of the particle
                // ---------------------------------
                float modTime   = time / timeFactor;
                float speed     = speed_angle_offset.x;
                float angle     = speed_angle_offset.y;
                float offset    = speed_angle_offset.z;
                float G         = gravity.x;
                float x0        = position.x;
                float y0        = position.y;

                // Calculations for the non-ending particle flow
                // -------------------------------------------------
                float offsetStart   = abs(offset) * lifetime;
                float offsetTime    = clamp(modTime - offsetStart, 0., 2e10);
                offsetTime          = mod(offsetTime, lifetime);

                // Moving emitter... The problem IS HERE
                // -------------------------------------------------
                if(modTime - offsetTime > deltaXYT.z ){
                    x0  = x0 + deltaXYT.x;
                    y0  = y0 + deltaXYT.y;
                }

                // Equations of parabolic shoot to set x and y position
                // -----------------------------------------------------
                float x = speed * cos(angle) * offsetTime + x0;
                float y = -.5 * G * pow(offsetTime, 2.) + speed * sin(angle) * offsetTime + y0;

                // Ratio canvas
                // ---------------------------------
                x /= ratio;

                // Printing particle
                // ---------------------------------
                gl_Position=vec4(x, y, 0, 1.);
            }`;

About my code :

The translation on the Y axis is creating line 50 with a setinterval for a slow visualization.

My solution is to create a deltaXYT uniform (line 380) which embedded the X delta, the Y delta, and the exact time (this.time) the delta position is applied to the X,Y position of each particle.

This technique is implemented in the getVertexShader function line 430 (Moving emitter)

As you can see, the result is not that i expect, because each particle doesn't memorize its own deltaXY in order to run its own way... So what you're seeing is a batch of young particles running on the most recent deltaXYT, and a batch of other particles running on the default deltaXYT line 155 (which brings no modification on position attribute)

I suppose i'm not in the right way, so did you have any suggestion to do this thing, which, at the beginning, didn't seem so hard.

Body:
Each particle should have a birth time, but also a birth position.
This position will change at every particle reborn and cannot be computed by the vertex shader. Especially if it is a mouse position, for example.
You need to store this new position somewhere.

One solution could be to store it in the attributes:

attribute vec2 attInitialPosition;

attribute vec2 attInitialSpeed;

attribute float attBirthTime;

Then the "reborn" logic can be delegated to Javascript code that will update the attributes once changed.

Of course, sending the whole Data Array for all the 500 particles is not a good idea.
Instead, we can just send what has changed.

To explain the trick in an easy way, let's assume we will create a new particle at each frame. That means that we will create particles at a rate of 60 per seconds if we are lucky.

Then, at first frame, you update the attributes of vertex 1, at frame 2 the attributes of vertex 2, etc...
Of course at frame 501 you update again the attributes of vertex 1 and so on.

With 500 particules, that means that each one will leave for 500 * 16 ms = 8 seconds.

And at each frame, you can update the vertex like this:

    public pushDataSubArray(data: Float32Array, start: number, end: number) {
        const { gl, vertBuff } = this
        gl.bindBuffer(gl.ARRAY_BUFFER, vertBuff)
        const subData = data.subarray(start * 5, end * 5)
        gl.bufferSubData(
            gl.ARRAY_BUFFER,
            start * Float32Array.BYTES_PER_ELEMENT * 5,
            subData
        )
    }

The subarray() method is super cool because it does not copy de data.
It's more like a window on a portion of your initial array.

Of course if you need more control, you will decide how many particles you update per frame depending on the rate and the lifetime you want. But I won't give you an example here because it complexifies the code and make it more difficult to understand.

Here is the vertex shader code:

uniform float uniTime;

attribute vec2 attInitialPosition;
attribute vec2 attInitialSpeed;
attribute float attBirthTime;

varying vec3 varColor;

const vec2 GRAVITY = vec2(0, -1) * 0.0000005;
const vec3 YELLOW = vec3(1.0, 1.0, 0.1);
const vec3 RED = vec3(0.8, 0.0, 0.0);

void main() {
    float t = uniTime - attBirthTime;
    float t2 = t * t;
    gl_Position = vec4(
        t2 * GRAVITY + t * attInitialSpeed + attInitialPosition,
        0.5, 1.0
    );
    gl_PointSize = 128.0 - 0.02 * t;
    float life = clamp(t * 0.005, 0.0, 1.0);
    float light = 11.0 - 10.0 * life * life;
    varColor = light * mix(YELLOW, RED, life);
}

See it in action here (move your mouse on the screen to change the birth location):

https://codepen.io/tolokoban/pen/zYPZJJX?editors=0010


问:
Stale items displayed in component
I have an app that displays some images. There are 12 images in total and each page displays 10 max. Number those images from 1 to 12, when change to page 2 you will see 2 wrappers showing image 1 and 2 instead of 11 and 12 for a very short time(you will get the right image eventually). This only happens when you change the page for the first time.

I'm confused about this behavior. Here's my website. And here is the GitHub repo.

My guess is that it's related to how React schedules updates. Or maybe I implement this functionality wrongly. It's harmless but you will be upset to have this kind of experience browsing the web.

Here's the component. I leave out the css part and something not that relevant to make the code shorter.

```<code>export default function ThumbPage() {
  const thumbData = useDataFetch(target);
  const [page, setPage] = useState([1, 1]);
  const [timeSort, setTimeSort] = useState(1);
  const [thumbDisp, setThumbDisp] = useState();

  useEffect(() => {
    setPage([1, thumbData ? Math.ceil(thumbData.length / 10) : 1]);
  }, [thumbData]);

  const changePage = (to) => {
    setPage([to, page[1]]);
  };
  useEffect(() => {
    let a = thumbData?.slice((page[0] - 1) * 10, page[0] * 10);
    setThumbDisp(a);
  }, [thumbData, timeSort, page]);
  if (thumbDisp) {
    return (
      <div className="aliContV" style={{ minWidth: "80%" }}>
        <Paper>
          <div>
            <div>
              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label">Time Ordering</InputLabel>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={timeSort}
                  label="TimeSort"
                  onChange={changeTimeSort}
                >
                  <MenuItem value={1}>New to Old</MenuItem>
                  <MenuItem value={-1}>Old to New</MenuItem>
                </Select>
              </FormControl>
            </div>
            <div>
              {thumbDisp ? (
                thumbDisp.map((image, index) => (
                  <ImageCard {...image} key={index}></ImageCard>
                ))
              ) : (
                <></>
              )}
            </div>
          </div>
          <PageSelector
            parentChangePage={changePage}
            maxPage={page[1]}
          ></PageSelector>
        </Paper>
      </div>
    );
  } else {
    return <CircularProgress />;
  }
}
</code>```

答:
Here is your problem:

```<code> <ImageCard {...image} key={index}></ImageCard>
</code>```

Don't use index as the key for ImageCard.
Replace it with the image URL or something that identifies the image.

Title: Stale items displayed in component

Body:
I have an app that displays some images. There are 12 images in total and each page displays 10 max. Number those images from 1 to 12, when change to page 2 you will see 2 wrappers showing image 1 and 2 instead of 11 and 12 for a very short time(you will get the right image eventually). This only happens when you change the page for the first time.

I'm confused about this behavior. Here's my website. And here is the GitHub repo.

My guess is that it's related to how React schedules updates. Or maybe I implement this functionality wrongly. It's harmless but you will be upset to have this kind of experience browsing the web.

Here's the component. I leave out the css part and something not that relevant to make the code shorter.

export default function ThumbPage() {
  const thumbData = useDataFetch(target);
  const [page, setPage] = useState([1, 1]);
  const [timeSort, setTimeSort] = useState(1);
  const [thumbDisp, setThumbDisp] = useState();

  useEffect(() => {
    setPage([1, thumbData ? Math.ceil(thumbData.length / 10) : 1]);
  }, [thumbData]);

  const changePage = (to) => {
    setPage([to, page[1]]);
  };
  useEffect(() => {
    let a = thumbData?.slice((page[0] - 1) * 10, page[0] * 10);
    setThumbDisp(a);
  }, [thumbData, timeSort, page]);
  if (thumbDisp) {
    return (

        <Paper>

              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label">Time Ordering</InputLabel>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={timeSort}
                  label="TimeSort"
                  onChange={changeTimeSort}
                >
                  <MenuItem value={1}>New to Old</MenuItem>
                  <MenuItem value={-1}>Old to New</MenuItem>
                </Select>
              </FormControl>

              {thumbDisp ? (
                thumbDisp.map((image, index) => (
                  <ImageCard {...image} key={index}></ImageCard>
                ))
              ) : (
                <></>
              )}

          <PageSelector
            parentChangePage={changePage}
            maxPage={page[1]}
          ></PageSelector>
        </Paper>

    );
  } else {
    return <CircularProgress />;
  }
}

Body:
Here is your problem:

 <ImageCard {...image} key={index}></ImageCard>

Don't use index as the key for ImageCard.
Replace it with the image URL or something that identifies the image.


问:
Pandas/Python - Dataframe transpose/pivot
I have a dataframe from "df.groupby("symbol").tail(2)" such as below

ID
symbol
prices

0
BNBBTC
0.009545

1
BNBBTC
0.009455

2
ONEUSDT
0.220050

3
ONEUSDT
0.220055

and I would like to transpose/pivot the data to get

ID
symbol
Last_Price
Current_Price

0
BNBBTC
0.009545
0.009455

1
ONEUDST
0.220050
0.220055

Is it achievable with Pandas?

Thanks

答:
Maybe you can use groupby + agg:

```<code>new_df = df.groupby('symbol')['prices'].agg(Last_Price='first', Current_Price='last').reset_index()
</code>```

Output:

```<code>>>> new_df
    symbol  Last_Price  Current_Price
0   BNBBTC    0.009545       0.009455
1  ONEUSDT    0.220050       0.220055
</code>```

Body:
Maybe you can use groupby + agg:

new_df = df.groupby('symbol')['prices'].agg(Last_Price='first', Current_Price='last').reset_index()

Output:

>>> new_df
    symbol  Last_Price  Current_Price
0   BNBBTC    0.009545       0.009455
1  ONEUSDT    0.220050       0.220055


问:
jquery .load() google docs form
i have a form created via google docs like https://spreadsheets.google.com/spreadsheet/embeddedform?formkey=dFgwMWhsallRZ2ViMWNaSVF1VmF2d0E6MQ.

is it possible to load this page into a div with jquery:

var content='https://spreadsheets.google.com/spreadsheet/embeddedform?formkey=dFgwMWhsallRZ2ViMWNaSVF1VmF2d0E6MQ';

$('#some_elem').load(content);

update: #some_elem is a dynamically created element.

答: I'm not aware of Google Doc's form creation, what scripts it's possible to use there, etc but it should work, as long as they are on the same domain. But why don't you just try it?</p>

Title: jquery .load() google docs form


问:
Can individual bubbles in a chartjs bubble chart have labels?
I'm creating a bubble chart using chartjs.  I am able to create tooltips that describe each of the bubbles, but users of my chart may not be able to hover over it to see the tooltip.  The BubbleData object format doesn't include a label element (I put one in anyway - no luck), I've tried the "labels" element for the Chart Data object (even though the docs say this is for Category labels - you never know!), and everything I can think of to put label on the bubble.

Is there a tooltip configuration that makes all the tooltips visible at all times?  This would work for me as well.

Thanks;

Glenn

答:
The sytax has changed with chart.js V3 in a few places so I thought I'd share my variation on the chosen answer.

```<code>Chart.register({
   id: 'permanentLabel',
   afterDatasetsDraw: function (chart, args, options) {
     var ctx = chart.ctx

     chart.data.datasets.forEach(function (dataset, i) {
       var meta = chart.getDatasetMeta(i)
       if (meta.type == 'bubble') {
         meta.data.forEach(function (element, index) {
           ctx.textAlign = 'center'
           ctx.textBaseline = 'middle'
           var position = element.tooltipPosition()
           ctx.fillText(dataset.data[index].label.toString(), position.x, position.y - dataset.data[index].r - Chart.defaults.font.size)
         })
       }
     })
   },
 })
</code>```

Body:
The sytax has changed with chart.js V3 in a few places so I thought I'd share my variation on the chosen answer.

Chart.register({
   id: 'permanentLabel',
   afterDatasetsDraw: function (chart, args, options) {
     var ctx = chart.ctx

     chart.data.datasets.forEach(function (dataset, i) {
       var meta = chart.getDatasetMeta(i)
       if (meta.type == 'bubble') {
         meta.data.forEach(function (element, index) {
           ctx.textAlign = 'center'
           ctx.textBaseline = 'middle'
           var position = element.tooltipPosition()
           ctx.fillText(dataset.data[index].label.toString(), position.x, position.y - dataset.data[index].r - Chart.defaults.font.size)
         })
       }
     })
   },
 })


问:
Detect (or forbid) game bar within browsers
I'm relying on browsers full screen mode for one of my projects.

I just discovered that using the windows "game bar" (windows + G) let the users browse away without any trace.
So here is my question: From within a browser, how could it be possible to detect (or forbid) the "game bar" usage.

Note: the game bar's shortcut is configurable, so listening for the key-press events of windows + G is not enough.

答:
You could use document.visibilityState. From MDN:

The Document.visibilityState read-only property returns the visibility of the document, that is in which context this element is now visible. It is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering.

Something like this:

const isVisible = () => document.visibilityState === "visible";
```


问:
Remove duplicates records in a MySQL table with key but not primary key
I need to remove duplicate records (just to keep one copy) from a MySQL table in MyISAM format. I have read many questions in Stackoverflow about similar issues but always the people use an ID field as unique id or similar and I haven't this field because my "Key" could be duplicated. I want to remove rows with the 'Fecha' and 'Equip' duplicated.

```<code>CREATE TABLE `pfc` (
`Fecha` datetime NOT NULL,
`Equip` int(10) unsigned NOT NULL,
`Value` double NOT NULL,
KEY `Fecha` (`Fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AVG_ROW_LENGTH=21 ROW_FORMAT=FIXED;
</code>```

An example table data:

```<code>Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
06/02/2011 0:00:11 |  22   |  29.0
</code>```

The result should be:

```<code>Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
</code>```

This structure is not possible to change. I cannot use PRIMARY KEY or UNIQUE INDEX solutions. To create a temporal table without duplicates and then rename would be a poor solutions also, because the KEY and another parameters will be lost.

Thanks

答:
```<code>ALTER IGNORE TABLE `pfc` ADD UNIQUE(`Fetcha`, `Equip`);
</code>```

That will keep the first record it finds and remove duplicates from your table.

From MySQL manual:

IGNORE is a MySQL extension to standard SQL. It controls how ALTER
  TABLE works if there are duplicates on unique keys in the new table or
  if warnings occur when strict mode is enabled. If IGNORE is not
  specified, the copy is aborted and rolled back if duplicate-key errors
  occur. If IGNORE is specified, only the first row is used of rows with
  duplicates on a unique key. The other conflicting rows are deleted.
  Incorrect values are truncated to the closest matching acceptable
  value.

Edit:

To create an exact copy of your table, use the following:

CREATE TABLE table_copy SELECT * FROM pfc;

That will copy the table structure and the data. After that, run the ALTER command to add the UNIQUE constraint and filter out the records that are duplicated.

Body:
I need to remove duplicate records (just to keep one copy) from a MySQL table in MyISAM format. I have read many questions in Stackoverflow about similar issues but always the people use an ID field as unique id or similar and I haven't this field because my "Key" could be duplicated. I want to remove rows with the 'Fecha' and 'Equip' duplicated.

CREATE TABLE `pfc` (
`Fecha` datetime NOT NULL,
`Equip` int(10) unsigned NOT NULL,
`Value` double NOT NULL,
KEY `Fecha` (`Fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AVG_ROW_LENGTH=21 ROW_FORMAT=FIXED;

An example table data:

Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
06/02/2011 0:00:11 |  22   |  29.0

The result should be:

Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3

This structure is not possible to change. I cannot use PRIMARY KEY or UNIQUE INDEX solutions. To create a temporal table without duplicates and then rename would be a poor solutions also, because the KEY and another parameters will be lost.

Thanks

Body:
ALTER IGNORE TABLE `pfc` ADD UNIQUE(`Fetcha`, `Equip`);

That will keep the first record it finds and remove duplicates from your table.

From MySQL manual:

IGNORE is a MySQL extension to standard SQL. It controls how ALTER
  TABLE works if there are duplicates on unique keys in the new table or
  if warnings occur when strict mode is enabled. If IGNORE is not
  specified, the copy is aborted and rolled back if duplicate-key errors
  occur. If IGNORE is specified, only the first row is used of rows with
  duplicates on a unique key. The other conflicting rows are deleted.
  Incorrect values are truncated to the closest matching acceptable
  value.

Edit:

To create an exact copy of your table, use the following:

CREATE TABLE table_copy SELECT * FROM pfc;

That will copy the table structure and the data. After that, run the ALTER command to add the UNIQUE constraint and filter out the records that are duplicated.


问:
Removing rows out of a table given a certain condition
I have the following table "HAVE":

ID
Date

Test_5000_ABC_2022-01
01MAY2020

Test_12345_XYZ_2022-05
15OCT2021

Test_00000_UMX_2022-12
01SEP2021

Test_00000_UMX_2022-12
01DEC2022

The last part of a string in the "ID column" there is always a year and a month delimited by "-", while the column "date" has a date in the "DDMMYYY" format.

Now, I would want to delete all entries from this table where the date from the "ID" column is after the date (after the month and year) in the "date" column and save it as a new table. So, basically, my WANT table would look like this:

ID
Date

Test_00000_UMX_2022-12
01DEC2022

I appreciate any kind of help, as I am very new to SAS. Thank you!

答:
Extract date from the ID variable

Align the date to beginning of the month

Compare as needed

```<code>data have;
infile cards dlm='09'x truncover;
input ID : $23. Date : date9.;
cards;
Test_5000_ABC_2022-01   01MAY2020
Test_12345_XYZ_2022-05  15OCT2021
Test_00000_UMX_2022-12  01SEP2021
Test_00000_UMX_2022-12  01DEC2022
;;;;
run;

data want;
set have;

date_id = mdy(input(scan(id, -1, "-_"), 8.) , 1, input(scan(id, -2, "-_"), 8.) );

*check your condition;
if date_id > intnx('month', date, 0, 'b') then flag=1;

*if date_id > intnx('month', date, 0, 'b') then delete;

format date_id date yymmdds10.;

run;
</code>```

Body:
Extract date from the ID variable

Align the date to beginning of the month

Compare as needed

data have;
infile cards dlm='09'x truncover;
input ID : $23. Date : date9.;
cards;
Test_5000_ABC_2022-01   01MAY2020
Test_12345_XYZ_2022-05  15OCT2021
Test_00000_UMX_2022-12  01SEP2021
Test_00000_UMX_2022-12  01DEC2022
;;;;
run;

data want;
set have;

date_id = mdy(input(scan(id, -1, "-_"), 8.) , 1, input(scan(id, -2, "-_"), 8.) );

*check your condition;
if date_id > intnx('month', date, 0, 'b') then flag=1;

*if date_id > intnx('month', date, 0, 'b') then delete;

format date_id date yymmdds10.;

run;


问:
How to pull a range of data (plus/minus) around a specific date in SQL
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

```<code>SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)
</code>```

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

答:
The problem is in the JOIN segment: you need to JOIN by customer_id and not dates:</p>
```<code>ON b.customer_id = a.customer_id
</code>```

Body:
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

Body:
The problem is in the JOIN segment: you need to JOIN by customer_id and not dates:

ON b.customer_id = a.customer_id


问:
python optional caching of function
What's the best way to cache a function in python with an optional caching parameter?

I've a function which performs a database request and does not take any arguments.
Most of the times it's okay if the function uses the cached result but sometimes I want to send a new database request.

from functools import lru_cache

@lru_cache
def my_database_request_function(use_cache: bool = False):

    if use_cache:
    # takes response from cache
    else:
    # makes database request

    return response

```

The implementation above won't work because the second time the functions gets called with the use_cache=False parameter it will not make a new request.

答:
Use lru_cache's cache_clear() to clear the cached value and force a new retrieval:

[...] The decorator also provides a cache_clear() function for clearing or invalidating the cache. [...]

Demo:

```<code>from functools import lru_cache

what = 1     # global value for demo purposes

@lru_cache
def my_database_request_function():
    return what

print(my_database_request_function())

what = 42                                  # change value

print(my_database_request_function())      # gets cached value

my_database_request_function.cache_clear() # clear cache

print(my_database_request_function())      # not cached
</code>```

Output:

```<code>1
1  # after changing the global 'what' variable, still gets cached result
42 # after .cache_clear()
</code>```

Title: python optional caching of function

Body:
What's the best way to cache a function in python with an optional caching parameter?

I've a function which performs a database request and does not take any arguments.
Most of the times it's okay if the function uses the cached result but sometimes I want to send a new database request.

from functools import lru_cache

@lru_cache
def my_database_request_function(use_cache: bool = False):

    if use_cache:
    # takes response from cache
    else:
    # makes database request

    return response

The implementation above won't work because the second time the functions gets called with the use_cache=False parameter it will not make a new request.

Body:
Use lru_cache's cache_clear() to clear the cached value and force a new retrieval:

[...] The decorator also provides a cache_clear() function for clearing or invalidating the cache. [...]

Demo:

from functools import lru_cache

what = 1     # global value for demo purposes

@lru_cache
def my_database_request_function():
    return what

print(my_database_request_function())

what = 42                                  # change value

print(my_database_request_function())      # gets cached value

my_database_request_function.cache_clear() # clear cache

print(my_database_request_function())      # not cached

Output:

1
1  # after changing the global 'what' variable, still gets cached result
42 # after .cache_clear()


问:
Why isn't there space between my menu items?
I'm making a test site to get better at html and CSS. I found a design and started to try to make that design right now I have this:

But as you can see the navbar items are way too close to each other and for some reason the icon wont show up.

can someone explain to me why the navbar items wont get space between each other and why my icon is not showing up? Thanks in advance.

nav {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
}

nav .logo {
  font-size: 2.5rem;
}

nav ul {
  display: flex;
  list-style-type: none;
  padding: 0;
}

nav li a {
  color: white;
  padding: 1rem 2rem;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class='container'>
  <div class='logo'><i class="fa-solid fa-otter"></i>Sea otters</div>

  <ul>
    <li a href='#'>Home</li>
    <li a href='#'>Species</li>
    <li a href='#'>Habitat</li>
    <li a href='#'>Behavior</li>
    <li a href='#' class='highlight'>Ecology</li>
  </ul>
</nav></code>```

答:
```<code><nav class='container'>
   <div class='logo'><i class="fa-solid fa-otter"></i>Sea otters</div>
      <ul>
         <li><a href='#'>Home</a></li>
         <li><a href='#'>Species</a></li>
         <li><a href='#'>Habitat</a></li>
         <li><a href='#'>Behavior</a></li>
         <li><a href='#' class='highlight'>Ecology</a></li>
     </ul>
</nav>
</code>```

Body:
I'm making a test site to get better at html and CSS. I found a design and started to try to make that design right now I have this:

But as you can see the navbar items are way too close to each other and for some reason the icon wont show up.

can someone explain to me why the navbar items wont get space between each other and why my icon is not showing up? Thanks in advance.

nav {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
}

nav .logo {
  font-size: 2.5rem;
}

nav ul {
  display: flex;
  list-style-type: none;
  padding: 0;
}

nav li a {
  color: white;
  padding: 1rem 2rem;
  text-decoration: none;
}

Sea otters

Home

Species

Habitat

Behavior

Ecology


问:
Can't update a document in CosmosDB from node.js app
This is most likely a rookie mistake but any help would be appreciated....  I am trying to update a document in cosmosDB from my node app (using PUG).  But when I invoke the replace method...

```<code>async updateItem(item) {
  const itemId = item.ticketId;
  const {resource: replaced } = await this.tickets.item(itemId,itemId).replace(item);
  return replaced;
}
</code>```

I get the following error:

```<code>RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: TypeError:
 C:\Users\donko\OneDrive\vscode\appstart\views\editticket.pug:30
   28|       .form-group
   29|         label.ticket-label(for='fk_ticket_status') Ticket Status :
 >    30|         select(name="fk_ticket_status" value=ticket.fk_ticket_status required
</code>```

So my question is why is the call to the CosmosDb replace method failing on the page?  I haven't gotten to the point where my code should be re-rendering the page?  the item object is called via my router as:

```<code>  async updateTicket(req, res) {
   await this.ticketModel.updateItem(req.body);
</code>```

By comparison, my addItem function works just fine:

```<code>async addItem(item) {
  debug('Adding a ticket to the database')
  item.submitted_date = Date.now();
  item.fk_ticket_status = 1;
  item.assigned_to = '';
  item.parent = '';
  const { resource: doc } = await this.tickets.items.create(item)
  return doc
}
</code>```

答:
I figured out the problem. According to Partial document update in Azure Cosmos DB, to update a document using replace, the client needs to read it, update it locally and then send it over the wire as a whole document Replace API call.  When I tried this, it worked fine:</p>
```<code>const oldDoc = await this.getItem(itemId);
const newDoc = oldDoc;
newDoc.updated_date = Date.now();
//... more updates here
const {resource: replaced } = await this.tickets.item(itemId, itemId).replace(newDoc);
</code>```

Body:
This is most likely a rookie mistake but any help would be appreciated....  I am trying to update a document in cosmosDB from my node app (using PUG).  But when I invoke the replace method...

async updateItem(item) {
  const itemId = item.ticketId;
  const {resource: replaced } = await this.tickets.item(itemId,itemId).replace(item);
  return replaced;
}

I get the following error:

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: TypeError:
 C:\Users\donko\OneDrive\vscode\appstart\views\editticket.pug:30
   28|       .form-group
   29|         label.ticket-label(for='fk_ticket_status') Ticket Status :
 >    30|         select(name="fk_ticket_status" value=ticket.fk_ticket_status required

So my question is why is the call to the CosmosDb replace method failing on the page?  I haven't gotten to the point where my code should be re-rendering the page?  the item object is called via my router as:

  async updateTicket(req, res) {
   await this.ticketModel.updateItem(req.body);

By comparison, my addItem function works just fine:

async addItem(item) {
  debug('Adding a ticket to the database')
  item.submitted_date = Date.now();
  item.fk_ticket_status = 1;
  item.assigned_to = '';
  item.parent = '';
  const { resource: doc } = await this.tickets.items.create(item)
  return doc
}

Body:
I figured out the problem. According to Partial document update in Azure Cosmos DB, to update a document using replace, the client needs to read it, update it locally and then send it over the wire as a whole document Replace API call.  When I tried this, it worked fine:

const oldDoc = await this.getItem(itemId);
const newDoc = oldDoc;
newDoc.updated_date = Date.now();
//... more updates here
const {resource: replaced } = await this.tickets.item(itemId, itemId).replace(newDoc);