问:
Add discount per certain number of products on the cheapest products in WooCommerce
I'm adding the discount rule for every 3 products: 3,6,9,12,15.. on the cart and it should apply to discount 50% only the cheapest products.

So if you have 9, only the 3 cheapest gets 50% off.

This code applies a discount to all products, so it should only be every 3 products

add_action('woocommerce_cart_calculate_fees', 'ts_add_custom_discount', 10, 1 );
function ts_add_custom_discount( $wc_cart ){
    $discount = 0;
    $product_ids = array();
    $item_prices = array();
    $in_cart = false;

    foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
        $cart_product = $cart_item['data'];
        if ( has_term( 'get2', 'product_cat', $cart_product->get_id() ) ) { // get2 selected category
            $in_cart = true;
        }else {
            $in_cart = true;
            $product_ids[] = $cart_product->get_id();
            $item_prices[$cart_product->get_id()] = $cart_product->get_price();
        }
    }

    if( $in_cart ) {

        $count_ids = count($product_ids);

        asort( $item_prices ); //Sort the prices from lowest to highest

        $cartQuantity = WC()->cart->cart_contents_count;

        $count = 0;

        if( $count_ids > 3 || $cartQuantity >= 3 ) {
           foreach( $item_prices as $id => $price ) {
                if( $count >= 1 ) {
                    break;
                }
                //$product = wc_get_product( $id );
                //$price = $product->get_price();
                $discount -= ($price * 50) /100;
                $count++;
           }
       }

    }

    if( $discount != 0 ){
        $wc_cart->add_fee( 'Discount', $discount, true  );
    }
}
```

I have attached a screenshot, you can see there is a red outline for every 3rd cheapest product.

答:
This answer will apply a 50% discount per 3 products on the cheapest products. (explanation via comment tags added to the code)

So you get:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // Products in cart
    $products_in_cart = count( $cart->get_cart() );

    // Every so many products
    $every = 3;

    // When products in cart greater than or equal to every so many products
    if ( $products_in_cart >= $every ) {
        // Set array
        $product_prices = array();

        // Loop though cart items
        foreach ( $cart->get_cart() as $cart_item ) {
            // Product
            $product = $cart_item['data'];

            // Get price
            $product_price = $product->get_price();

            // Push
            $product_prices[] = $product_price;
        }

        // Sort: low to high
        asort( $product_prices );

        // Number of products receive a discount
        $products_receive_discount = floor( $products_in_cart / $every );

        // Set variable
        $total = 0;

        // Loop trough
        foreach ( array_slice( $product_prices, 0, $products_receive_discount ) as $product_price ) {
            // Calculate
            $total += $product_price;
        }

        // Calculate discount
        $discount = ( $total * 50 ) / 100;

        // Discount
        $cart->add_fee( __( 'Discount', 'woocommerce' ), -$discount, true );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
```

Body:
I'm adding the discount rule for every 3 products: 3,6,9,12,15.. on the cart and it should apply to discount 50% only the cheapest products.

So if you have 9, only the 3 cheapest gets 50% off.

This code applies a discount to all products, so it should only be every 3 products

add_action('woocommerce_cart_calculate_fees', 'ts_add_custom_discount', 10, 1 );
function ts_add_custom_discount( $wc_cart ){
    $discount = 0;
    $product_ids = array();
    $item_prices = array();
    $in_cart = false;

    foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
        $cart_product = $cart_item['data'];
        if ( has_term( 'get2', 'product_cat', $cart_product->get_id() ) ) { // get2 selected category
            $in_cart = true;
        }else {
            $in_cart = true;
            $product_ids[] = $cart_product->get_id();
            $item_prices[$cart_product->get_id()] = $cart_product->get_price();
        }
    }

    if( $in_cart ) {

        $count_ids = count($product_ids);

        asort( $item_prices ); //Sort the prices from lowest to highest

        $cartQuantity = WC()->cart->cart_contents_count;

        $count = 0;

        if( $count_ids > 3 || $cartQuantity >= 3 ) {
           foreach( $item_prices as $id => $price ) {
                if( $count >= 1 ) {
                    break;
                }
                //$product = wc_get_product( $id );
                //$price = $product->get_price();
                $discount -= ($price * 50) /100;
                $count++;
           }
       }

    }

    if( $discount != 0 ){
        $wc_cart->add_fee( 'Discount', $discount, true  );
    }
}

I have attached a screenshot, you can see there is a red outline for every 3rd cheapest product.


来源: stackexchange

问:
Why is an excerpt projection not applied automatically for a Spring Data REST item resource?
I made a projection which should expose nested entities:

```<code>@Projection(name = "inlineBusiness", types = { UserModel.class })
public interface InlineBusinessUserModelProjection {

    String getUsername();

    String getFirstName();

    String getLastName();

    Date getBirthdate();

    String getEmail();

    BusinessModel getBusiness();
}
</code>```

And the service repository:

```<code>@RepositoryRestResource(collectionResourceRel = "users", path = "users",
       excerptProjection = InlineBusinessUserModelProjection.class)
public interface UserRepository extends BaseDAO<UserModel> {..}
</code>```

for /users it works fine, the business field is exposed with nested entity, but when I call /users/1- nothing, also all the custom methods.. Seems like projection isn't involved on any methods except of /users
Any ideas?

答:
I'm not going to argue with @Oliver Drotbohm, as this is indeed the correct answer, however, if you want a cheeky workaround, just define a getter for the entity field with a slightly different name (using the OP's example):

```<code>BusinessModel getBusinessInline() { return this.businessModel; }
</code>```

Will result in a JSON payload of:

```<code>{
    .
    .
    "businessInline": {"name":"stuff etc"}
    .
    .
}
</code>```

Presuming your consuming service will accept that, then its an option.

Not big or clever, but it works.

ContentLicense: CC BY-SA 3.0

Body:
I made a projection which should expose nested entities:

@Projection(name = "inlineBusiness", types = { UserModel.class })
public interface InlineBusinessUserModelProjection {

    String getUsername();

    String getFirstName();

    String getLastName();

    Date getBirthdate();

    String getEmail();

    BusinessModel getBusiness();
}

And the service repository:

@RepositoryRestResource(collectionResourceRel = "users", path = "users",
       excerptProjection = InlineBusinessUserModelProjection.class)
public interface UserRepository extends BaseDAO<UserModel> {..}

for /users it works fine, the business field is exposed with nested entity, but when I call /users/1- nothing, also all the custom methods.. Seems like projection isn't involved on any methods except of /users
Any ideas?

Body:
I'm not going to argue with @Oliver Drotbohm, as this is indeed the correct answer, however, if you want a cheeky workaround, just define a getter for the entity field with a slightly different name (using the OP's example):

BusinessModel getBusinessInline() { return this.businessModel; }

Will result in a JSON payload of:

{
    .
    .
    "businessInline": {"name":"stuff etc"}
    .
    .
}

Presuming your consuming service will accept that, then its an option.

Not big or clever, but it works.

ContentLicense: CC BY-SA 4.0


问:
FigureCanvasTkAgg resizes if its figure is refreshed
I am working on a matplotlib figure embedded in a tkinter gui in Python.

First a FigureCanvasTkAgg is created, which includes a previously created object, which contains a matplotlib figure and then it is drawn. This part works perfectly fine.
Afterwards I want to refresh the canvas / its content based on an user action. If the method to refresh the canvas is called, the figure object is refreshed and the canvas is redrawn.
This works as well, the figure is updated, but for some strange reason, the canvas resizes, so it shrinks to about one quarter of its original size. If I print the size of the canvas, I can see that its size changed.

I have tried to resize the canvas back to its original size after the refreshment, without success.

I would be thankful for any input. I have added a shortend version of my code.

    #canvas object which is displayed on the gui
    class Canvas:
        def __init__(self, parent):
            #the map_figure object is create
            self.map_figure = map_figure()
            #the matplotlib figure is extracted from the map_figure
            self.figure = self.map_figure.get_figure()
            #the canvas is created using the figure and the parent
            self.canvas = FigureCanvasTkAgg(self.figure, master=parent)
            #I tried both, to manually set the canvas size to the window dimensions (which are
            #described by w and h and using the .pack() parameters, both are working fine
            self.canvas.get_tk_widget().config(width=w,height=h)
            #self.canvas.get_tk_widget().pack(fill='both', expand=True)
            self.canvas.get_tk_widget().pack()
            #canvas is drawn
            self.canvas.draw()
            #its size is printed
            print(self.get_size())

       def refresh(self, parent, point):
            #the map_figure of the canvas is refresh
            self.map_figure.refresh(data)
            #the matplotlib figure is extracted  again
            self.canvas.figure = self.map_figure.get_figure()
            #canvas is redrawn
            self.canvas.draw()
            #the canvas size is now different for some reason even after calling
            #self.canvas.get_tk_widget().config(width=w,height=h) before this again
            print(self.canvas.get_width_height())

    #the map_figure class if relevant
    class map_figure:
        def __init__(self, data):
            self.figure = self.create_figure(data)

        def get_figure(self):
            return self.figure

        def create_figure(self, data):
            #creating a matplotlib figure, closing if there was one before
            plt.close(fig=None)
            fig = plt.figure()
            #creating a figure using the data here
            return fig

        #refreshing the figure using new data
        def refresh(self, data):
            self.figure = self.create_figure(data)
```

Here are also two picture to visualize my problem:

Before

After

答:
clf()

Instead of closing the figure each time you refresh it, you could clear it:

```<code>def create_figure(self, date):
    #creating a matplotlib figure, closing if there was one before
    try:
        self.figure.clf()
        fig = self.figure
    except:
        fig = plt.figure()
    #creating a figure using the data here
    ...
</code>```

Body:
I am working on a matplotlib figure embedded in a tkinter gui in Python.

First a FigureCanvasTkAgg is created, which includes a previously created object, which contains a matplotlib figure and then it is drawn. This part works perfectly fine.
Afterwards I want to refresh the canvas / its content based on an user action. If the method to refresh the canvas is called, the figure object is refreshed and the canvas is redrawn.
This works as well, the figure is updated, but for some strange reason, the canvas resizes, so it shrinks to about one quarter of its original size. If I print the size of the canvas, I can see that its size changed.

I have tried to resize the canvas back to its original size after the refreshment, without success.

I would be thankful for any input. I have added a shortend version of my code.

    #canvas object which is displayed on the gui
    class Canvas:
        def __init__(self, parent):
            #the map_figure object is create
            self.map_figure = map_figure()
            #the matplotlib figure is extracted from the map_figure
            self.figure = self.map_figure.get_figure()
            #the canvas is created using the figure and the parent
            self.canvas = FigureCanvasTkAgg(self.figure, master=parent)
            #I tried both, to manually set the canvas size to the window dimensions (which are
            #described by w and h and using the .pack() parameters, both are working fine
            self.canvas.get_tk_widget().config(width=w,height=h)
            #self.canvas.get_tk_widget().pack(fill='both', expand=True)
            self.canvas.get_tk_widget().pack()
            #canvas is drawn
            self.canvas.draw()
            #its size is printed
            print(self.get_size())

       def refresh(self, parent, point):
            #the map_figure of the canvas is refresh
            self.map_figure.refresh(data)
            #the matplotlib figure is extracted  again
            self.canvas.figure = self.map_figure.get_figure()
            #canvas is redrawn
            self.canvas.draw()
            #the canvas size is now different for some reason even after calling
            #self.canvas.get_tk_widget().config(width=w,height=h) before this again
            print(self.canvas.get_width_height())

    #the map_figure class if relevant
    class map_figure:
        def __init__(self, data):
            self.figure = self.create_figure(data)

        def get_figure(self):
            return self.figure

        def create_figure(self, data):
            #creating a matplotlib figure, closing if there was one before
            plt.close(fig=None)
            fig = plt.figure()
            #creating a figure using the data here
            return fig

        #refreshing the figure using new data
        def refresh(self, data):
            self.figure = self.create_figure(data)

Here are also two picture to visualize my problem:

Before

After

Body:
clf()

Instead of closing the figure each time you refresh it, you could clear it:

def create_figure(self, date):
    #creating a matplotlib figure, closing if there was one before
    try:
        self.figure.clf()
        fig = self.figure
    except:
        fig = plt.figure()
    #creating a figure using the data here
    ...


问:
How to store access tokens in Firebase back-end?
My React app uses Firebase Authentication and the Real-Time Database. I now need to access 3rd party services using OAuth 2.0. To do this securely, I am using the OAuth 2.0 Authorization Code Flow with Firebase Functions as my back-end:

React app gets an Authorization Code from the 3rd party.

Authorization code is passed to a Firebase function to get an access token.

But this is where I am stuck. How do I save the access token in the backend so that the React app can access the 3rd party resources? I don't want to store the access token in the React app because that's not secure.

How do I maintain a session in the back-end using Firebase Functions?

Should the session be tied to the React app instance or the Firebase user? The former approach would require a session cleanup. The latter has the advantage that new access tokens can be obtained using a refresh token. This way the user never has to login to the 3rd party again!

答:
OVERALL FACTORS

Typically these are the areas that your SPA Security choices influence, and there are trade offs:

Type of App

Strong Security

Hosting and Global Performance

Technical Simplicity

IN ALL CASES

Your app should:

Maintain a token for each user separately

You will want to identify users from tokens after login

OPTION 1: FRONT END MODEL / COOKIELESS

This involves using tokens in the browser and has these benefits:

Back end is static content only

Web resources can be deployed close to users via a CDN

You can use the OIDC Client library to manage security

This is widely used and should only be exploitable if your app has cross site scripting vulnerabilities. Some resources of mine:

SPA Goals

In Memory Authentication Code

Code Sample Write Up

OPTION 2: BACK END MODEL / AUTH COOKIES

This involves proxying via a back end and carrying tokens around in authentication cookies. I would use this model if developing an online banking app but for medium security apps it can add a lot of overhead. You may have to write more security code and it is possible to end up with a less secure solution than option 1:

Requires a proxy back end that runs code

The back end code may need to be clustered and globally distributed, to achieve good performance

You need to protect the auth cookie and deal with cross site request forgery risks

Out of interest the respected mod_auth_openidc library can be helpful for this type of solution.

BEST OF BOTH WORLDS

If using tokens in a browser is deemed unacceptable I would aim to follow option 1 as much as possible. Then implement option 2 as an additive step:

Deploy web static content separately to the code that does back end token management

Continue to use the OIDC Client library, and make the Authorization Code Exchange call your back end

The only difference to option 1 is that tokens are not available to browser code


问:
Tensorflow-gpu running issue
With:

Tensorflow-gpu 2.0.0

Windows 10 environment

NVIDIA GTX 1050 gpu

cuda 10.0 and  corresponding cudnn 7.6.5

I followed the official TF documentation for TF-gpu and I've tried to create and fit a simple CNN model (on a.py file, I've tried with a jupyter but the kernel always dies) but I got the following:

```<code>2020-02-06 23:57:14.420911: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll
2020-02-06 23:57:16.081396: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-02-06 23:57:16.861094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce GTX 1050 major: 6 minor: 1 memoryClockRate(GHz): 1.493
pciBusID: 0000:01:00.0
2020-02-06 23:57:16.861492: I tensorflow/stream_executor/platform/default/dlopen_checker_stub.cc:25] GPU libraries are statically linked, skip dlopen check.
2020-02-06 23:57:16.862290: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
2020-02-06 23:58:14.322053: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-02-06 23:58:14.324900: F tensorflow/stream_executor/lib/statusor.cc:34] Attempting to fetch value instead of handling error Internal: failed to get device attribute 13 for device 0: CUDA_ERROR_UNKNOWN: unknown error
</code>```

Does someone have an idea what to do exactly to make tf-gpu 2.0.0 run normally ? I've tested with 2.1.0 but the problem seems to persist.

答:
Providing the solution here even though it is present in Github, for the benefit of the Stackoverflow Community.

Installation of Tensorflow_GPU : 2.1.0 with the below combination has resolved  CUDA_ERROR_UNKNOWN issue.

Python version   : 3.7.6

Compiler : MSVC 2017

CUDA : 10.1

cuDNN : 7.6.5

Please refer tested build configurations for windows CPU and GPU.

Title: Tensorflow-gpu running issue

Body:
With:

Tensorflow-gpu 2.0.0

Windows 10 environment

NVIDIA GTX 1050 gpu

cuda 10.0 and  corresponding cudnn 7.6.5

I followed the official TF documentation for TF-gpu and I've tried to create and fit a simple CNN model (on a.py file, I've tried with a jupyter but the kernel always dies) but I got the following:

2020-02-06 23:57:14.420911: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll
2020-02-06 23:57:16.081396: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-02-06 23:57:16.861094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce GTX 1050 major: 6 minor: 1 memoryClockRate(GHz): 1.493
pciBusID: 0000:01:00.0
2020-02-06 23:57:16.861492: I tensorflow/stream_executor/platform/default/dlopen_checker_stub.cc:25] GPU libraries are statically linked, skip dlopen check.
2020-02-06 23:57:16.862290: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
2020-02-06 23:58:14.322053: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-02-06 23:58:14.324900: F tensorflow/stream_executor/lib/statusor.cc:34] Attempting to fetch value instead of handling error Internal: failed to get device attribute 13 for device 0: CUDA_ERROR_UNKNOWN: unknown error

Does someone have an idea what to do exactly to make tf-gpu 2.0.0 run normally ? I've tested with 2.1.0 but the problem seems to persist.


问:
angular form with switcher with one input
I have component with switcher of parts, in which user should fill input field (T1, T2, T3).
T1 is opened by default. Earlier after filling Part1 user clicked submit and data goes to server, than clicked T2 - submit, than clicked T3 - submit. Now I need send values, after filling all parts, but when I fill T1 submit button becomes active, click T2 input field becomes clear and submit button becomes disabled.

Is it possible with form with one input to get all 3 values and than send them on submit.

```<code><ng-container *ngIf="value.PartId == activatedPart">
    <app-send-value [activatedPart]="activatedPart"></app-send-value>
</ng-container>

and in <app-send-value> I have form with mat-input

    <form (ngSubmit)="onSubmit()" >
        <mat-form-field>
            <input matInput
                   type="number"
                   required
                   value="{{value}}"
                   [(ngModel)]="value">
        </mat-form-field>

            <button type="submit"
                    [disabled]="sendValue.invalid">
                Submit
            </button>
    </form>
</code>```

my form

答:
Update based on your stackblitz example : Please modify as follows

send.component.html :

```<code><form class="value-form"
          id="sendValue"
          (ngSubmit)="onSubmit()"
          autocomplete="off"
          #sendValue="ngForm">
            <input matInput
                   class="value-input"
                   type="number"
                   name="value"
           placeholder="fill the field"
           onfocus="this.value=''"
                   id="value"
                   required
                   [(ngModel)]="value[activatedPart - 1]">
        <div class="send-form-buttons">
            <button class="app-btn-success-sm"
                    type="submit"
                    [disabled]="checkDisabled()">
                Submit
            </button>
        </div>
    </form>
</code>```

send.component.ts :

```<code>import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-send',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent implements OnInit {
  constructor() { }

@Input() activatedPart = 0;
@Input() switchesLength = 0;
value: number[] = [];

  ngOnInit() {
  }

  get formInvalid() {
        return false
    }

  onSubmit() {
        if (this.formInvalid) return;

    console.log(this.value)
  }

  checkDisabled() {
    if(Array.isArray(this.value) && this.value.length === 3) {
      return !this.value.every(function(element) {return !!element;});
    }
    return true;
  }
}
</code>```

You can clear the values on submit simply by writing this.value = []; on submit function and removing  onfocus="this.value=''" from <input> tag

Body:
I have component with switcher of parts, in which user should fill input field (T1, T2, T3).
T1 is opened by default. Earlier after filling Part1 user clicked submit and data goes to server, than clicked T2 - submit, than clicked T3 - submit. Now I need send values, after filling all parts, but when I fill T1 submit button becomes active, click T2 input field becomes clear and submit button becomes disabled.

Is it possible with form with one input to get all 3 values and than send them on submit.

<ng-container *ngIf="value.PartId == activatedPart">
    <app-send-value [activatedPart]="activatedPart"></app-send-value>
</ng-container>

and in <app-send-value> I have form with mat-input

    <form (ngSubmit)="onSubmit()" >
        <mat-form-field>
            <input matInput
                   type="number"
                   required
                   value="{{value}}"
                   [(ngModel)]="value">
        </mat-form-field>

            <button type="submit"
                    [disabled]="sendValue.invalid">
                Submit
            </button>
    </form>

my form

Body:
Update based on your stackblitz example : Please modify as follows

send.component.html :

<form class="value-form"
          id="sendValue"
          (ngSubmit)="onSubmit()"
          autocomplete="off"
          #sendValue="ngForm">
            <input matInput
                   class="value-input"
                   type="number"
                   name="value"
           placeholder="fill the field"
           onfocus="this.value=''"
                   id="value"
                   required
                   [(ngModel)]="value[activatedPart - 1]">
        <div class="send-form-buttons">
            <button class="app-btn-success-sm"
                    type="submit"
                    [disabled]="checkDisabled()">
                Submit
            </button>
        </div>
    </form>

send.component.ts :

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-send',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent implements OnInit {
  constructor() { }

@Input() activatedPart = 0;
@Input() switchesLength = 0;
value: number[] = [];

  ngOnInit() {
  }

  get formInvalid() {
        return false
    }

  onSubmit() {
        if (this.formInvalid) return;

    console.log(this.value)
  }

  checkDisabled() {
    if(Array.isArray(this.value) && this.value.length === 3) {
      return !this.value.every(function(element) {return !!element;});
    }
    return true;
  }
}

You can clear the values on submit simply by writing this.value = []; on submit function and removing  onfocus="this.value=''" from <input> tag


问:
How can ı ajax request with json?
I have a API . I want to get data and ı want to that data write to input. I used AJAX but nothing happened when click submit button </p>

```<code>$(document).ready(function () {

     $('#ajaxBtn').click(function(){
        $.ajax("https://jsonplaceholder.typicode.com/todos/1",
        {
            dataType: 'json', // type of response data
            timeout: 500,     // timeout milliseconds
            success: function (data,status,xhr) {   // success callback function
                $('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
            },
            error: function (jqXhr, textStatus, errorMessage) { // error callback
                $('p').append('Error: ' + errorMessage);
            }
        });
     });

    });

    <input type="button" id="ajaxBtn" value="Send Ajax request" />
<p>
</p>
</code>```

答:
1) Include the jquery library if not
2) Add script tag

<input type="button" id="ajaxBtn" value="Send Ajax request" />

```

Title: How can ı ajax request with json?

Body:
I have a API . I want to get data and ı want to that data write to input. I used AJAX but nothing happened when click submit button

$(document).ready(function () {

     $('#ajaxBtn').click(function(){
        $.ajax("https://jsonplaceholder.typicode.com/todos/1",
        {
            dataType: 'json', // type of response data
            timeout: 500,     // timeout milliseconds
            success: function (data,status,xhr) {   // success callback function
                $('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
            },
            error: function (jqXhr, textStatus, errorMessage) { // error callback
                $('p').append('Error: ' + errorMessage);
            }
        });
     });

    });

    <input type="button" id="ajaxBtn" value="Send Ajax request" />

Body:
1) Include the jquery library if not
2) Add script tag

<script src="https://code.jquery.com/jquery-3.5.1.js" ></script>
<script>
    jQuery(document).ready(function ($) {

        $('#ajaxBtn').click(function(){
            $.ajax("https://jsonplaceholder.typicode.com/todos/1",
                {
                    dataType: 'json', // type of response data
                    // timeout: 500,     // timeout milliseconds
                    success: function (data,status,xhr) {   // success callback function
                        console.log(data);
                        $('p').append('Todo ID: ' + data.id + ' | Title:' + data.title + ' | UserId: ' + data.userId);
                    },
                    error: function (jqXhr, textStatus, errorMessage) { // error callback
                        $('p').append('Error: ' + errorMessage);
                    }
                });
        });

    });
</script>

<input type="button" id="ajaxBtn" value="Send Ajax request" />
<p>
</p>


问:
Make POST request from HTML
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

```<code><a href='http:/test_url:5002/api/GetFile'></a>
</code>```

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.

答:
Thats what forms are for. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
Just create a form with a submit button. You can also specify if you want to open the requested URL in a new tab with the target attribute.

Title: Make POST request from HTML

Body:
I want to make an HTTP POST request from an HTML anchor tag that has the URL in its href attribute.

How can I make it use POST instead of GET?

I also want to set parameters in the body of the request. How can I do that?

I want to find a way to include them in the HTML tag itself, not in a JavaScript file.


问:
Get Current User in a Blazor component
I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.

For a Razor Page, the current user name can be accessed with Context.User.Identity.Name, but that doesn't seem to work in a Blazor component.  I've tried injecting HttpContext into the component but the Context is null at runtime.

As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications.  Answers tailored to that use case would also be appreciated.

答:
I've had a similar requirement and have been using:

```<code>var authstate = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authstate.User;
var name = user.Identity.Name;
</code>```

I already had an AuthenticationStateProvider in my startup.cs and added it to the constructor of my custom class.

Title: Get Current User in a Blazor component

Body:
I've had a similar requirement and have been using:

var authstate = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authstate.User;
var name = user.Identity.Name;

I already had an AuthenticationStateProvider in my startup.cs and added it to the constructor of my custom class.


问:
Having problem with routes.rb. No route matches show action
I am trying to make a button. When you click it, a modal should appear with a form.

I created the button:

```<code><li>
<%= link_to content_tag(:i, nil, class: "fa fa-plus") + " New Rule",new_rule_correlation_engine_rule_path, class: "pull-right panel-button", 'data-toggle' => "modal", 'data-target' => "#new_rule_correlation_engine_rule_modal", "data-backdrop" => "static" %>
</li>
</code>```

And in the routes.rb, I defined the first route (the resources part was already there):

```<code>get 'correlation_engine_rules/new_rule' => 'correlation_engine_rules#new_rule', as: 'new_rule_correlation_engine_rule'

    resources :correlation_engine_rules do
      post :apply, on: :collection
    end
</code>```

I also created a file named new_rule, with a logger at the beginning to know if this is being loaded. Apparently, when I click the button, it load that file, because I see the logger, but then I get this error:

```<code><ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"correlation_engine_rules"} missing required keys: [:id]>
</code>```

So, the routes matches with my first line, but it seems it is also trying to execute the method show, I guess because of the resources lines below mine. At first I had my route below that part, then I saw this error and I put it before, as stated in the routing rails guide, but I still get this error. I thought that when 1 route matches, it stop looking for more, maybe I am wrong but I don't get what is the problem. Thanks.

solution: i finally solved this by entering the new route inside the resources block, like this:

```<code>resources :correlation_engine_rules do
      post :apply, on: :collection
      get :new_rule, on: :collection
end
</code>```

and then i'm calling it like new_rule_correlation_engine_rules_path.

答:
have you tried specifying the http method GET?,something like this

<%= link_to content_tag(:i, nil, class: "fa fa-plus") + " New Rule",new_rule_correlation_engine_rule_path, method: :get, class: "pull-right panel-button", 'data-toggle' => "modal", 'data-target' => "#new_rule_correlation_engine_rule_modal", "data-backdrop" => "static" %>

```

Body:
I am trying to make a button. When you click it, a modal should appear with a form.

I created the button:

<%= link_to content_tag(:i, nil, class: "fa fa-plus") + " New Rule",new_rule_correlation_engine_rule_path, class: "pull-right panel-button", 'data-toggle' => "modal", 'data-target' => "#new_rule_correlation_engine_rule_modal", "data-backdrop" => "static" %>

And in the routes.rb, I defined the first route (the resources part was already there):

get 'correlation_engine_rules/new_rule' => 'correlation_engine_rules#new_rule', as: 'new_rule_correlation_engine_rule'

    resources :correlation_engine_rules do
      post :apply, on: :collection
    end

I also created a file named new_rule, with a logger at the beginning to know if this is being loaded. Apparently, when I click the button, it load that file, because I see the logger, but then I get this error:

<ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"correlation_engine_rules"} missing required keys: [:id]>

So, the routes matches with my first line, but it seems it is also trying to execute the method show, I guess because of the resources lines below mine. At first I had my route below that part, then I saw this error and I put it before, as stated in the routing rails guide, but I still get this error. I thought that when 1 route matches, it stop looking for more, maybe I am wrong but I don't get what is the problem. Thanks.

solution: i finally solved this by entering the new route inside the resources block, like this:

resources :correlation_engine_rules do
      post :apply, on: :collection
      get :new_rule, on: :collection
end

and then i'm calling it like new_rule_correlation_engine_rules_path.


问:
How to enable text selection modal(copy/paste/select) in flutter webview?
Can anyone please share the code snippet to enable the text selection model in the webview of the flutter? Till now I get that by default webview only has one gesture recognizer i.e. vertical scrolling. If anyone have code for LongPressGestureRecognizer please share it here. Thanks in advance.

答:
It was solved by changing the webview package. Currently I am using flutter_inappwebview package and it's working fine.
The thing was the previous webview package didn't support the touch and hold gestures.
Also, native webview for Android and iOS could also be used but no overlay can be shown in that case.

The above package works fine on both cases.


问:
How to call a function from html button
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

```<code><html>
    <head>
        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

     <script>
             function delete(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="delete(9)">Erase</button>
    </body>

</html>
</code>```

答:
You need to change the delete to another name function , delete is an operator , you can see the list of operators here : Expressions and operators

```<code>function ajaxCall(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="ajaxCall(9)">Erase</button>
    </body>
</code>```

Title: How to call a function from html button

Body:
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

        <button type="button" onclick="delete(9)">Erase</button>

Body:
You need to change the delete to another name function , delete is an operator , you can see the list of operators here : Expressions and operators

function ajaxCall(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="ajaxCall(9)">Erase</button>
    </body>


问:
How to write highlighted data into excel file using python?
I have written python program for highlighting some of keywords.please view screenshot.help me out how to write this line in excel using python same as

```<code>from termcolor import colored
text=[!['Hi How are you.fine by the grace of god?'][1]][1]
l1=['grace','god']
formattedText = []
for t in text.lower().split():
if t in l1:
    formattedText.append(colored(t,'white','on_red'))
else:
    formattedText.append(t)

print(" ".join(formattedText))
</code>```

答:
Okay so i have used openpyxl in this code as its more convenient and I will give you full guide on how to highlight cells with it.

first you import should be :

```<code>from openpyxl.styles import PatternFill
import openpyxl
</code>```

then you might know this but still, I am telling you need to give path and select the active sheet out of that excel file:

```<code>path = r"THENAMEOFYOURFILE.xlsx"
wb_obj = openpyxl.load_workbook(path, data_only=True)
sheet_obj = wb_obj.active
</code>```

when you have the sheet active you need to bring colors I have two sample colors you can try search online for more colors.

```<code>ligth_red_color = PatternFill(start_color="FFC7CE", fill_type="solid")
green_color = PatternFill(start_color='8BB048', fill_type="solid")
</code>```

now you can specify the cell you want to highlight by giving its row and column like for C3 its 3rd row and 3rd column.

```<code>cellC3 = sheet_obj.cell(row=3, column=3)
</code>```

then you can take the fill component of the cellc3 and give it the value of any of the 2 sample color I gave before.

```<code>cellC3.fill = ligth_red_color   #change the color of cell C3 to red
cellC3.fill = green_color   #change the color of cell C3 to green
</code>```

now don't forget to save the file otherwise the changes won't be saved

```<code>sheet_obj.save(r"FINALFILENAME.xlsx")
</code>```

Hope you find these codes and explanation helpful

Body:
I have written python program for highlighting some of keywords.please view screenshot.help me out how to write this line in excel using python same as

from termcolor import colored
text=[!['Hi How are you.fine by the grace of god?'][1]][1]
l1=['grace','god']
formattedText = []
for t in text.lower().split():
if t in l1:
    formattedText.append(colored(t,'white','on_red'))
else:
    formattedText.append(t)

print(" ".join(formattedText))

Body:
Okay so i have used openpyxl in this code as its more convenient and I will give you full guide on how to highlight cells with it.

first you import should be :

from openpyxl.styles import PatternFill
import openpyxl

then you might know this but still, I am telling you need to give path and select the active sheet out of that excel file:

path = r"THENAMEOFYOURFILE.xlsx"
wb_obj = openpyxl.load_workbook(path, data_only=True)
sheet_obj = wb_obj.active

when you have the sheet active you need to bring colors I have two sample colors you can try search online for more colors.

ligth_red_color = PatternFill(start_color="FFC7CE", fill_type="solid")
green_color = PatternFill(start_color='8BB048', fill_type="solid")

now you can specify the cell you want to highlight by giving its row and column like for C3 its 3rd row and 3rd column.

cellC3 = sheet_obj.cell(row=3, column=3)

then you can take the fill component of the cellc3 and give it the value of any of the 2 sample color I gave before.

cellC3.fill = ligth_red_color   #change the color of cell C3 to red
cellC3.fill = green_color   #change the color of cell C3 to green

now don't forget to save the file otherwise the changes won't be saved

sheet_obj.save(r"FINALFILENAME.xlsx")

Hope you find these codes and explanation helpful


问:
SQL query not executing as whole
So I have a query that should add Primary Key to the Id field:

```<code>IF NOT EXISTS(SELECT *
              FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
              WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE BTS.dbo.CAL
    ALTER COLUMN Intern INT NOT NULL;

    ALTER TABLE BTS.dbo.CAL
        ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);

    CREATE INDEX CAL$01
    ON CAL (Intern);
END
</code>```

The problem is that when I chose all this code and execute (F5), I get this error:

Whereas when I'm choosing every statement one by one it works as expected:

I am sure that the IF works as expected

I tried to use GO between statements, it's not allowed.

I should execute this code on a large number of tables

Maybe I don't know something about how SQL Server Management Studio executes statements

答:
Even though question is answer, I just wanted to add one more option.

You can separate statments into two separate batches, so that your change is available to the subsequent batch

CREATE TABLE #test(a int null);

-- DDL Changes
if exists(SELECT 1)
BEGIN

ALTER TABLE #test ALTER COLUMN a int not null;

END
GO

-- Index changes
if exists(SELECT 1)
BEGIN
    ALTER TABLE #test ADD CONSTRAINT PK_test PRIMARY KEY(a)
END
GO
```

Title: SQL query not executing as whole

Body:
So I have a query that should add Primary Key to the Id field:

IF NOT EXISTS(SELECT *
              FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
              WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE BTS.dbo.CAL
    ALTER COLUMN Intern INT NOT NULL;

    ALTER TABLE BTS.dbo.CAL
        ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);

    CREATE INDEX CAL$01
    ON CAL (Intern);
END

The problem is that when I chose all this code and execute (F5), I get this error:

Whereas when I'm choosing every statement one by one it works as expected:

I am sure that the IF works as expected

I tried to use GO between statements, it's not allowed.

I should execute this code on a large number of tables

Maybe I don't know something about how SQL Server Management Studio executes statements


答:
This is a way you could do it</p>

```<code> <form  method="POST" action="/api/PostFile">

<!-- with input in between -->

<!-- and a submit button-->

</form>
</code>```

Title: Make POST request from HTML

Body:
This is a way you could do it

 <form  method="POST" action="/api/PostFile">

<!-- with input in between -->

<!-- and a submit button-->

</form>


答:
The problem is that int columns are stored in int32 or int64 numpy arrays, and neither dtype has a concept of empty value. It is not an accident if an int column is converted to a floating point type as soon as you add a NaN value to it.

With recent versions of Pandas >=0.24, you can try to use the nullable integer extension dtype:

```<code>df['A'] = pd.Series(np.where(df['A'].isna()|(df['A']==''), pd.NA,
           df.loc[df['A']!='','A'].apply(int).reindex(df.index)
           .fillna(0)), dtype=pd.Int64Dtype)
</code>```

But beware is is explicitely declared to be experimental:

Note

IntegerArray is currently experimental. Its API or implementation may change without warning.

Title: Python dataframe - .astype(str).astype(int) gives error ValueError: invalid literal for int() with base 10: ''

Body:
I am trying to convert a dataframe column from object to int using:

df['col'].astype(str).astype(int)

but I am getting an error

ValueError: invalid literal for int() with base 10: ''

due to the fact that some of the elements are empty. How can I deal with that and overcome / get rid off this error?

Here is what a part of my column looks like:

 0001081316
 0001081316
 0001609253
 0000928022
 0000928022
 0000916457
 0000916457
 0000916457
 0000916457
 0000016732
 0001094093
 0000911177
 0000816284
 0000816284
 0000879573
 0000018808
 0000785080
 0000018926
 0000018926
 0000018926
 0000018926
 0001319048
 0001627223
 0000895126
 0000895126
 0000895126
 0000895126
 0000895126
 0000716133
 0000716133
 0000716133
 0000716133
 0000716133
 0000020520
 0000020520
 0000020520
 0000020520
 0001400891
 0001400891
 0001400891
 0000020947
 0000764065
 0000764065
 0000764065
 0000764065
 0000764065
 0000021344
 0000021344
 0000215466
 0000215466
 0001158324
 0001323653
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0000918040
 0000023194
 0000023217
 0001358071
 0001163165
 0001163165
 0001710366
 0000897732
 0000016918
 0000016918
 0000732834
 0000732834
 0000024741
 0001018980
 0000025305
 0000025305
 0001051470
 0001051470
 0000912513
 0000028630
 0000916540
 0000931336
 0001571996
 0000027904
 0000027996
 0001090012
 0001090012
 0001090012
 0001090012
 0000949039
 0000949039
 0000949039
 0000715957
 0000715957
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000030554
 0000030554
 0000030554
 0000030554
 0001326160
 0001326160
 0001092839
 0000821189
 0000821189
 0000821189
 0000821189
 0000821189
 0000821189
 0000750199
 0000033213
 0000033213
 0000915389
 0001600470
 0001066107
 0001066107
 0001590895
 0000032604
 0000032604
 0001591763
 0001591763
 0000880285
 0000880285
 0000880285
 0001161154
 0001161154
 0001161154
 0001024401
 0001024401
 0000033619
 0001532063
 0001532063
 0001532063
 0000887936
 0001062613
 0000880430
 0000880430
 0000038074
 0000038074

 0000831259
 0000831259
 0000831259
 0000831259

Body:
The problem is that int columns are stored in int32 or int64 numpy arrays, and neither dtype has a concept of empty value. It is not an accident if an int column is converted to a floating point type as soon as you add a NaN value to it.

With recent versions of Pandas >=0.24, you can try to use the nullable integer extension dtype:

df['A'] = pd.Series(np.where(df['A'].isna()|(df['A']==''), pd.NA,
           df.loc[df['A']!='','A'].apply(int).reindex(df.index)
           .fillna(0)), dtype=pd.Int64Dtype)

But beware is is explicitely declared to be experimental:

Note

IntegerArray is currently experimental. Its API or implementation may change without warning.


问:
php implode breaks on spaces

I have an array of strings, and these strings have spaces in them. For example:

```<code>$arr = array('bob', 'john smith', 'grease monkey', 'etc');
</code>```

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

```<code>$str = "bob|john";
</code>```

If I try:

```<code>$arr = array('bob', 'john', 'grease monkey', 'etc');
</code>```

and implode, I get:

```<code>$str = "bob|john|grease";
</code>```

Edit: I'm actually trying to set it to the value of a hidden field:

```<code><input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />
</code>```

答:
Worked for me. Try not reassigning your variables:</p>

```<code><?php
$str = array('bob', 'john smith', 'grease monkey', 'etc');
$new_str = implode('|', $str);

echo $new_str;
?>
</code>```

Title: php implode breaks on spaces

Body:
I have an array of strings, and these strings have spaces in them. For example:

$arr = array('bob', 'john smith', 'grease monkey', 'etc');

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

$str = "bob|john";

If I try:

$arr = array('bob', 'john', 'grease monkey', 'etc');

and implode, I get:

$str = "bob|john|grease";

Edit: I'm actually trying to set it to the value of a hidden field:

<input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />

Body:
Worked for me. Try not reassigning your variables:

<?php
$str = array('bob', 'john smith', 'grease monkey', 'etc');
$new_str = implode('|', $str);

echo $new_str;
?>


问:
Apply a gradle plugin conditionally depending on a flavour folder contents
I'm in a need of conditionally applying the com.google.gms.google-services plugin in my project only to certain flavours.

I managed to achieve this analogically to this approach, but it works for static values only (meaning I need to hardcode the flavours that I want to add this plugin to).

I'm searching for a solution that would allow me applying the plugin only if a certain flavour contains the google-services.json file (or it is in the project's inheritance tree), so the solution is flexible and does not require keeping the list up-to-date.

I managed to scan for the existence of this file for all the build variants using the project.android.applicationVariants property, but this check is being done already once all the plugins are applied. This means that the results of this scan are not needed anymore.

Is there any way to use the project's applicationVariants property on an earlier stage, before applying the plugin?

答:
After all I followed the solution that enables the plugin, but disables the task it introduces for flavours that should not have the plugin enabled. Since it can be done in the same project.android.applicationVariants block as I checked for the google-services.json file presence, it turned out to be a perfect solution for that case.

See more: https://stackoverflow.com/a/49542745/3187706


问:
In a Svelte readable store array, How can I update only one item without touching the others?
I guess this question is more on JS sysntax, but I have a store array like this:

```<code>export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})
</code>```

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

```<code>arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})
</code>```

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

答:
You can access the actual value of the readable store also inside the callback. Then you can update the existing array without replacing all:</p>

```<code><script>
    import {readable} from 'svelte/store'

    let intervalHandle
    const arr = new readable(['Start'], (set) => {
        intervalHandle = setInterval(() => {
            set([...$arr, 'Another value'])
        }, 1000)
    })

</script>

<h1>Readable demo</h1>
<button on:click={() => clearInterval(intervalHandle)}>Stop it</button>
{#each $arr as item}
<div>{item}</div>
{/each}
</code>```

Body:
I guess this question is more on JS sysntax, but I have a store array like this:

export const store = readable( {id: 0, value: 0} , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        set({id: 0, value: data});
    }
})

The store defines its set method to update the value from a websockets connection.
How can I do the same but with a store array? Something like:

arr = [];
for(i=0; i<numberOfItems; i++) {
    arr = [...arr,{id: i, value: 0}];
}

export const store = readable( [{arr}] , set => {
    let socket = new WebSocket("ws://localhost:65432");
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var channel = data.channel;
        set({id: data.channel, value: data.value});
    }
})

Here is where I dont manage to "set" o the array, and without having to declare the whole array every update.

Body:
You can access the actual value of the readable store also inside the callback. Then you can update the existing array without replacing all:

<script>
    import {readable} from 'svelte/store'

    let intervalHandle
    const arr = new readable(['Start'], (set) => {
        intervalHandle = setInterval(() => {
            set([...$arr, 'Another value'])
        }, 1000)
    })

</script>

<h1>Readable demo</h1>
<button on:click={() => clearInterval(intervalHandle)}>Stop it</button>
{#each $arr as item}
<div>{item}</div>
{/each}


问:
C# how to read a low quality barcode?
Goal:

I am aiming to read a bar code that has poor quality. Code works fine if the bar code is in it's highest quality.

Image:

Code:

To crop the barcode code:

```<code>    private Point LocationXY;
    private Point LocationX1Y1;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            LocationXY = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle currentSelection = GetRect();
        if (currentSelection != Rectangle.Empty)
        {
            e.Graphics.DrawRectangle(Pens.Red, currentSelection);
        }
    }

    private void pictureBox2_Paint(object sender, PaintEventArgs e)
    {
        var src = GetRect();

        if (src == Rectangle.Empty) return;

        var des = new Rectangle(0, 0, src.Width, src.Height);

        e.Graphics.DrawImage(pictureBox1.Image,
            des, src, GraphicsUnit.Pixel);
    }

    private Rectangle GetRect()
    {
        return new Rectangle(
            Math.Min(LocationXY.X, LocationX1Y1.X),
            Math.Min(LocationXY.Y, LocationX1Y1.Y),
            Math.Abs(LocationXY.X - LocationX1Y1.X),
            Math.Abs(LocationXY.Y - LocationX1Y1.Y)
            );
    }

    private Bitmap GetCroppedImage()
    {
        var des = GetRect();

        if (des == Rectangle.Empty) return null;

        var b = new Bitmap(des.Width, des.Height);

        using (var g = Graphics.FromImage(b))
        {
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, des.Width, des.Height), des, GraphicsUnit.Pixel);
        }
        return b;

    }
</code>```

Class where the image is saved and able to return the image:

```<code>public class BarcodeImage
{
    private static Image _image;

    public static Image _Image
    {
        get
        {
            return _image;
        }
        set
        {
            _image = value;
        }
    }
}
</code>```

Here I click a button to save the image to class and check the barcode:

```<code>   private void checkBarcode_Click(object sender, EventArgs e)
    {
        BarcodeImage._Image = GetCroppedImage();

        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode((Bitmap)BarcodeImage._Image);
        if (result != null)
        {
            MessageBox.Show(result.ToString());
        }
    }
</code>```

Using the code:

Here I highlight the barcode and save it into picturebox2.

Next by clicking checkBarcode_Click it should show the barcode value - but it doesen't. Becasue of the quality of the image.

I have tested it with high quality barcode images and it works fine!

Question:

How can I improve the quality of the Cropped Image and return me the Barcode value?

Edit: 29/05/2020

I have asked a new question on this community seeing if I can I increase size of the cropped image. But that did not improve anything:

https://stackoverflow.com/a/62068397/12485722

High Quality Barcode:

The image is taken out from specific program.

I print screen the images and they must be specifically like this this:

But it does not detect the barcode.

This is a zoomed in version of the image using 2x on the program:

Unfortunately I cannot use the x2 zoom in option as some of the data will move on the image and not giving an accurate final image. On top of that, the barcode is recognized!

答:
So... If you will get your x2 zoomed image, divide it by 2 horizontally, and crop barcode, zxing will provide you the info! So all you need - crop without any distortions.
So, all you need to finish your task - just find the borders of barcode (i think it may be hardcoded if you will have the same format all the time). If no - it is easy to scan image and find it by black pixels from bottom right corner.

Text version of code :

```<code>static void Main(string[] args)
    {
        var barcodeFull = Bitmap.FromFile("barcode-x2-zoomed-dividedx2.jpg");
        var cropFromPoint = new Point(64, 578);
        var cropSize = new Size(360, 142);

        var barcode = CropAtRect((Bitmap)barcodeFull, new Rectangle(cropFromPoint, cropSize));
        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode(barcode);
        if (result != null)
        {
            Console.WriteLine("result : "+result.Text);
        }

        Console.ReadLine();
    }

    public static Bitmap CropAtRect(Bitmap b, Rectangle r)
    {
        Bitmap nb = new Bitmap(r.Width, r.Height);
        using (Graphics g = Graphics.FromImage(nb))
        {
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }
    }
</code>```

Title: C# how to read a low quality barcode?

Body:
Goal:

I am aiming to read a bar code that has poor quality. Code works fine if the bar code is in it's highest quality.

Image:

Code:

To crop the barcode code:

    private Point LocationXY;
    private Point LocationX1Y1;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            LocationXY = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle currentSelection = GetRect();
        if (currentSelection != Rectangle.Empty)
        {
            e.Graphics.DrawRectangle(Pens.Red, currentSelection);
        }
    }

    private void pictureBox2_Paint(object sender, PaintEventArgs e)
    {
        var src = GetRect();

        if (src == Rectangle.Empty) return;

        var des = new Rectangle(0, 0, src.Width, src.Height);

        e.Graphics.DrawImage(pictureBox1.Image,
            des, src, GraphicsUnit.Pixel);
    }

    private Rectangle GetRect()
    {
        return new Rectangle(
            Math.Min(LocationXY.X, LocationX1Y1.X),
            Math.Min(LocationXY.Y, LocationX1Y1.Y),
            Math.Abs(LocationXY.X - LocationX1Y1.X),
            Math.Abs(LocationXY.Y - LocationX1Y1.Y)
            );
    }

    private Bitmap GetCroppedImage()
    {
        var des = GetRect();

        if (des == Rectangle.Empty) return null;

        var b = new Bitmap(des.Width, des.Height);

        using (var g = Graphics.FromImage(b))
        {
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, des.Width, des.Height), des, GraphicsUnit.Pixel);
        }
        return b;

    }

Class where the image is saved and able to return the image:

public class BarcodeImage
{
    private static Image _image;

    public static Image _Image
    {
        get
        {
            return _image;
        }
        set
        {
            _image = value;
        }
    }
}

Here I click a button to save the image to class and check the barcode:

   private void checkBarcode_Click(object sender, EventArgs e)
    {
        BarcodeImage._Image = GetCroppedImage();

        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode((Bitmap)BarcodeImage._Image);
        if (result != null)
        {
            MessageBox.Show(result.ToString());
        }
    }

Using the code:

Here I highlight the barcode and save it into picturebox2.

Next by clicking checkBarcode_Click it should show the barcode value - but it doesen't. Becasue of the quality of the image.

I have tested it with high quality barcode images and it works fine!

Question:

How can I improve the quality of the Cropped Image and return me the Barcode value?

Edit: 29/05/2020

I have asked a new question on this community seeing if I can I increase size of the cropped image. But that did not improve anything:

https://stackoverflow.com/a/62068397/12485722

High Quality Barcode:

The image is taken out from specific program.

I print screen the images and they must be specifically like this this:

But it does not detect the barcode.

This is a zoomed in version of the image using 2x on the program:

Unfortunately I cannot use the x2 zoom in option as some of the data will move on the image and not giving an accurate final image. On top of that, the barcode is recognized!

Body:
So... If you will get your x2 zoomed image, divide it by 2 horizontally, and crop barcode, zxing will provide you the info! So all you need - crop without any distortions.
So, all you need to finish your task - just find the borders of barcode (i think it may be hardcoded if you will have the same format all the time). If no - it is easy to scan image and find it by black pixels from bottom right corner.

Text version of code :

static void Main(string[] args)
    {
        var barcodeFull = Bitmap.FromFile("barcode-x2-zoomed-dividedx2.jpg");
        var cropFromPoint = new Point(64, 578);
        var cropSize = new Size(360, 142);

        var barcode = CropAtRect((Bitmap)barcodeFull, new Rectangle(cropFromPoint, cropSize));
        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode(barcode);
        if (result != null)
        {
            Console.WriteLine("result : "+result.Text);
        }

        Console.ReadLine();
    }

    public static Bitmap CropAtRect(Bitmap b, Rectangle r)
    {
        Bitmap nb = new Bitmap(r.Width, r.Height);
        using (Graphics g = Graphics.FromImage(nb))
        {
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }
    }


问:
Node.js console.log - Is it possible to update a line rather than create a new line?
My node.js application has a lot of console logs, which are important for me to see (it's quite a big app so runs for a long time and I need to know that things are still progressing) but I'm ending up with thousands of lines of console logs.

Is it somehow possible to do a console.update that erases/replaces a console line rather than creating a new line?

答:
Just use \r to terminate your line:

```<code>process.stdout.write('text\r');
</code>```

Here's a simple example (wall clock):

```<code>setInterval(() => process.stdout.write(`clock: ${new Date()}\r`), 1000);
</code>```

Body:
Just use \r to terminate your line:

process.stdout.write('text\r');

Here's a simple example (wall clock):

setInterval(() => process.stdout.write(`clock: ${new Date()}\r`), 1000);


问:
Reshape pandas df of x,y,z in columns to x index, y header, and z values
I have a pandas df with x (latitudes), y (longitudes), and z (topography/elevation).

I want to plot a 3D surface plot but to do that I need a 2D z array whereas I have a 1D array (1 column).

Is there a way to pivot the dataframe so that the latitudes are the index, longitudes are the header and z are the values in the table?

I tried:

```<code>newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
</code>```

but it gives me an index error:

```<code>Pt_Longitude  Pt_Latitude  topography    Coordinated_Universal_Time  S
0    272.799970   -45.261200     2670.92  2009-07-20T12:12:00.90412170  1
1    272.800520   -45.261986     2677.35  2009-07-20T12:12:00.90412170  2
2    272.798841   -45.261578     2670.04  2009-07-20T12:12:00.90412170  3
3    272.799396   -45.260423     2663.68  2009-07-20T12:12:00.90412170  4
4    272.801063   -45.260832     2671.67  2009-07-20T12:12:00.90412170  5
Traceback (most recent call last):
  File "catalan.py", line 28, in <module>
    newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5923, in pivot
    return pivot(self, index=index, columns=columns, values=values)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 450, in pivot
    return indexed.unstack(columns)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\series.py", line 3550, in unstack
    return unstack(self, level, fill_value)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 419, in unstack
    constructor=obj._constructor_expanddim,
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 141, in __init__
    self._make_selectors()
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 176, in _make_selectors
    mask.put(selector, True)
IndexError: index 571859901 is out of bounds for axis 0 with size 571829246
</code>```

答: Why not just ...plt.plot_surface(*list(df.values), ...)?

Body:
I have a pandas df with x (latitudes), y (longitudes), and z (topography/elevation).

I want to plot a 3D surface plot but to do that I need a 2D z array whereas I have a 1D array (1 column).

Is there a way to pivot the dataframe so that the latitudes are the index, longitudes are the header and z are the values in the table?

I tried:

newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')

but it gives me an index error:

Pt_Longitude  Pt_Latitude  topography    Coordinated_Universal_Time  S
0    272.799970   -45.261200     2670.92  2009-07-20T12:12:00.90412170  1
1    272.800520   -45.261986     2677.35  2009-07-20T12:12:00.90412170  2
2    272.798841   -45.261578     2670.04  2009-07-20T12:12:00.90412170  3
3    272.799396   -45.260423     2663.68  2009-07-20T12:12:00.90412170  4
4    272.801063   -45.260832     2671.67  2009-07-20T12:12:00.90412170  5
Traceback (most recent call last):
  File "catalan.py", line 28, in <module>
    newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5923, in pivot
    return pivot(self, index=index, columns=columns, values=values)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 450, in pivot
    return indexed.unstack(columns)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\series.py", line 3550, in unstack
    return unstack(self, level, fill_value)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 419, in unstack
    constructor=obj._constructor_expanddim,
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 141, in __init__
    self._make_selectors()
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 176, in _make_selectors
    mask.put(selector, True)
IndexError: index 571859901 is out of bounds for axis 0 with size 571829246


问:
Can ngForIn be used in angular 4?
I am trying to iterate over the properties of an object using *ngFor but using in. When I try to do this

```<code>@Controller({
  selector: 'sample-controller',
  template: `
    <ul>
      <li *ngFor="let i in obj">
        <b>{{i}}</b>: {{obj[i]}}
      </li>
    </ul>`
})
class SampleController {
  obj = {a: 1, b: 2}
}
</code>```

I get the error message:

Can't bind to 'ngForIn' since it isn't a known property of 'li'.

I have included FormsModule and BrowserModule in the imports section of the @NgModule for this component.

Is it possible to use ngForIn on li and if not is there an idiomatic alternative?

答:
Things have changed a bit (at Angular 9) so the answer by yurzi wont work but on the similar lines setting your 'forOf' value into 'super.ngForOf' will do the trick</p>

```<code>import {   ContentChildren,   Directive,   Input,   IterableDiffers,   NgIterable,   OnChanges,   SimpleChanges,   TemplateRef,   ViewChildren,   ViewContainerRef } from "@angular/core";

import { NgForOf } from "@angular/common";

export interface Selectable<T> {   selected: boolean;   isActive: boolean; }

@Directive({
 selector: "[optionsFor][[optionsForOf]]" })
 export class OptionsForDirective<T extends Selectable<any>,U extends NgIterable<T> = NgIterable<T>>
     extends NgForOf<T, U> implements OnChanges {

   _editMode = false;
   _forOf: Array<Selectable<any>>;

  @Input()
  set iefOptionsForOf(value: any) {
    this._forOf = value;
    console.log("set of: ", value);
  }

  @Input()
  set iefOptionsForEditMode(value: boolean) {
    this._editMode = value;
    console.log("set edit mode: ", value);
  }

  constructor(
    public _viewContainer2: ViewContainerRef,
    public _templateRef2: TemplateRef<any>,
    public _differs2: IterableDiffers   ) {
    super(_viewContainer2, _templateRef2, _differs2);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.optionsForOf) {
      const origNgForOf: Array<Selectable<any>> = this._forOf;
      let filtered = origNgForOf;
      if (origNgForOf) {
        filtered = origNgForOf.filter(s => {
          return this._editMode || s.isActive !== false;
        });
      }
      console.log("filtered", filtered);

      super.ngForOf = filtered as any;
    }
  }
}
</code>```

Title: Can ngForIn be used in angular 4?

Body:
I am trying to iterate over the properties of an object using *ngFor but using in. When I try to do this

@Controller({
  selector: 'sample-controller',
  template: `

        {{i}}: {{obj[i]}}

`
})
class SampleController {
  obj = {a: 1, b: 2}
}

I get the error message:

Can't bind to 'ngForIn' since it isn't a known property of 'li'.

I have included FormsModule and BrowserModule in the imports section of the @NgModule for this component.

Is it possible to use ngForIn on li and if not is there an idiomatic alternative?

Body:
Things have changed a bit (at Angular 9) so the answer by yurzi wont work but on the similar lines setting your 'forOf' value into 'super.ngForOf' will do the trick

import {   ContentChildren,   Directive,   Input,   IterableDiffers,   NgIterable,   OnChanges,   SimpleChanges,   TemplateRef,   ViewChildren,   ViewContainerRef } from "@angular/core";

import { NgForOf } from "@angular/common";

export interface Selectable<T> {   selected: boolean;   isActive: boolean; }

@Directive({
 selector: "[optionsFor][[optionsForOf]]" })
 export class OptionsForDirective<T extends Selectable<any>,U extends NgIterable<T> = NgIterable<T>>
     extends NgForOf<T, U> implements OnChanges {

   _editMode = false;
   _forOf: Array<Selectable<any>>;

  @Input()
  set iefOptionsForOf(value: any) {
    this._forOf = value;
    console.log("set of: ", value);
  }

  @Input()
  set iefOptionsForEditMode(value: boolean) {
    this._editMode = value;
    console.log("set edit mode: ", value);
  }

  constructor(
    public _viewContainer2: ViewContainerRef,
    public _templateRef2: TemplateRef<any>,
    public _differs2: IterableDiffers   ) {
    super(_viewContainer2, _templateRef2, _differs2);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.optionsForOf) {
      const origNgForOf: Array<Selectable<any>> = this._forOf;
      let filtered = origNgForOf;
      if (origNgForOf) {
        filtered = origNgForOf.filter(s => {
          return this._editMode || s.isActive !== false;
        });
      }
      console.log("filtered", filtered);

      super.ngForOf = filtered as any;
    }
  }
}


问:
 src won't be change using Java Script in [ View ] [ ASP.NET MVC ]
I try to detect if  src not found change it with another src using JQUERY, I work on ASP.NET MVC project, and the src come from Controller.

This is what I try :

HTML

@foreach (var item in ViewBag.DATA)
  {

if (item.IMG_FRMTR != null)

     {

      ViewBag.IMG = String.Format("data:image/jpg;base64," + Convert.ToBase64String(item.IMG_FRMTR));

     }

  }

   ```
</div>
</div>
</p>

<p><strong>JQUERY</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    function standby() {

        document.getElementById('IMG').src = 'https://www.google.com/images/srpr/logo11w.png';

    }</code>```

Controller Action

```<code>            ViewBag.DATA = PROF_model.Select(CIN);

            return View();
</code>```

PROF_model.Select Method

```<code>    public static List<FRMTR> Select(string CIN)
    {
        var R = (from P in SCHOOL_DB_Context.Con.FRMTRs where P.CIN_FRMTR == CIN select P).ToList();

        return R;
    }
</code>```

Please any help ?

Note : I look for a lot solution here in Stackoverflow but no one solve my problem

Thanks in advance <3

答:
Thanks for @Pete, he gaves me a great solution that is :

Using just HTML with Tag Helpers like this :

```

Title: <img> src won't be change using Java Script in [ View ] [ ASP.NET MVC ]

Body:
I try to detect if  src not found change it with another src using JQUERY, I work on ASP.NET MVC project, and the src come from Controller.

This is what I try :

HTML

@foreach (var item in ViewBag.DATA)
  {

if (item.IMG_FRMTR != null)

     {

      ViewBag.IMG = String.Format("data:image/jpg;base64," + Convert.ToBase64String(item.IMG_FRMTR));

     }

  }

JQUERY

    function standby() {

        document.getElementById('IMG').src = 'https://www.google.com/images/srpr/logo11w.png';

    }

Controller Action

            ViewBag.DATA = PROF_model.Select(CIN);

            return View();

PROF_model.Select Method

    public static List<FRMTR> Select(string CIN)
    {
        var R = (from P in SCHOOL_DB_Context.Con.FRMTRs where P.CIN_FRMTR == CIN select P).ToList();

        return R;
    }

Please any help ?

Note : I look for a lot solution here in Stackoverflow but no one solve my problem

Thanks in advance <3

Body:
Thanks for @Pete, he gaves me a great solution that is :

Using just HTML with Tag Helpers like this :

<img id="PROF_IMG" src="@(string.IsNullOrWhiteSpace(ViewBag.IMG)?"https://www.google.com/images/srpr/logo11w.png" : ViewBag.IMG)" style="width:200px;height:200px">


问:
Version mismatch while loading sklearn.ensemble RandomForestModel ( built on VM ), on docker
I have built a random forest model on VM. It has python 3.5.3, sklearn 0.0 and scikit-learn 0.22.2.post1. I am building a docker with python 3.6 Docker and installing the exact versions and packages as present on VM (Note: did pip freeze to requirement.txt and using that to install requirements on docker).

The error found when docker logs are checked after build is as follows:

```<code>**ModuleNotFoundError: No module named 'sklearn.ensemble._forest'**.
</code>```

I also tried building the same module with python 3.7 but i am not able to install python 3.5 or 3.7 on docker. The models are being stored as joblib files.

答: Use scikit-learn==0.20.4 package, it worked for me with python-3.7. The latest version 0.23.1 gives you 'sklearn.ensemble._forest' error. </p>

Body:
I have built a random forest model on VM. It has python 3.5.3, sklearn 0.0 and scikit-learn 0.22.2.post1. I am building a docker with python 3.6 Docker and installing the exact versions and packages as present on VM (Note: did pip freeze to requirement.txt and using that to install requirements on docker).

The error found when docker logs are checked after build is as follows:

**ModuleNotFoundError: No module named 'sklearn.ensemble._forest'**.

I also tried building the same module with python 3.7 but i am not able to install python 3.5 or 3.7 on docker. The models are being stored as joblib files.


问:
How to add event listener to the div element accessed with ref using react and typescript?
i want to add event listener to the div element using ref.

I add ref div_ref to Wrapper div and access that div_ref in  enableDragEventListeners method to add event listeners to that on componentmount.

Below is my code,

```<code>const SomeComponent: React.FC<any> = props => {
    const div_ref  = React.useRef(null);
    React.useEffect(() => {
        const enableDragEventListeners = () => {
            const div = dropRef.current;
            if (div) {
                div.addEventListener('dragenter', handleDragIn); // get error here
                div.addEventListener('dragleave', handleDragOut); //error here
                div.addEventListener('dragover', handleDrag);//error here
                div.addEventListener('drop', handleDrop);//error here
            }
        };
        enableDragEventListeners();
    }, []);

    return (
        <Wrapper ref={div_ref}>
           {dragging && <Overlay>{props.children}</Overlay>}
        </Wrapper>
    );
}
</code>```

But i get error property addEventListener doesnt exist on type 'never'. could someone help me fix this. thanks.

Edit: Complete code looks like this...i am implementing a draganddrop component so wrapping this around a component that wants to use this will be able to drag and drop files into it.

```<code>const DragAndDrop: React.FC<any> = props => {
    const dropRef = useRef(null);
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);
    React.useEffect(() => {
        // componentDidMount()
        const handleDrag = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
            }
        };

        const handleDragIn = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev + 1);
                if (e.dataTransfer.files) {
                    setDragging(true);
                }
            }
        };

        const handleDragOut = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev - 1);
                if (dragCounter === 0) {
                    setDragging(false);
                }
            }
        };

        const handleDrop = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragging(false);
                if (e.dataTransfer.files && e.dataTransfer.files.length > 0){
                    props.handle_drop(e);
                    e.dataTransfer.clearData();
                   setDragCounter(0);
                }
            }
       };
       const enableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           if (div) {
               div.addEventListener('dragenter', handleDragIn);
               div.addEventListener('dragleave', handleDragOut);
               div.addEventListener('dragover', handleDrag);
               div.addEventListener('drop', handleDrop);
           }
       };
       const disableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           div.removeEventListener('dragenter', handleDragIn);
           div.removeEventListener('dragleave', handleDragOut);
           div.removeEventListener('dragover', handleDrag);
           div.removeEventListener('drop', handleDrop);
       };
       setDragCounter(0);
       enableDragEventListeners();
       return () => {
           // componentWillUnmount()
           disableDragEventListeners();
       };
   }, [dragCounter, props]);

   return (
       <wrapper ref={dropRef}>
           {dragging && <Overlay>{props.children}</Overlay>}
       </Wrapper>
   );
};

const DropZone = styled.div``;

export default DragAndDrop;
</code>```

答:
Issue :

```<code>const div_ref = React.useRef(null); // < --- due to null it type of div_ref becomes null
</code>```

Solution :

```<code>const div_ref = React.useRef<any>(null); // <--- Provide type any
// OR
const div_ref = React.useRef<TYPE_OF_WRAPPER>(null); // <--- Provide the type of ref element
</code>```

Sample demo : (With div element, you can remove the type and check, it will throw the same error )

NOTE : And I think dropRef.current; should be div_ref.current;

Body:
i want to add event listener to the div element using ref.

I add ref div_ref to Wrapper div and access that div_ref in  enableDragEventListeners method to add event listeners to that on componentmount.

Below is my code,

const SomeComponent: React.FC<any> = props => {
    const div_ref  = React.useRef(null);
    React.useEffect(() => {
        const enableDragEventListeners = () => {
            const div = dropRef.current;
            if (div) {
                div.addEventListener('dragenter', handleDragIn); // get error here
                div.addEventListener('dragleave', handleDragOut); //error here
                div.addEventListener('dragover', handleDrag);//error here
                div.addEventListener('drop', handleDrop);//error here
            }
        };
        enableDragEventListeners();
    }, []);

    return (
        <Wrapper ref={div_ref}>
           {dragging && <Overlay>{props.children}</Overlay>}
        </Wrapper>
    );
}

But i get error property addEventListener doesnt exist on type 'never'. could someone help me fix this. thanks.

Edit: Complete code looks like this...i am implementing a draganddrop component so wrapping this around a component that wants to use this will be able to drag and drop files into it.

const DragAndDrop: React.FC<any> = props => {
    const dropRef = useRef(null);
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);
    React.useEffect(() => {
        // componentDidMount()
        const handleDrag = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
            }
        };

        const handleDragIn = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev + 1);
                if (e.dataTransfer.files) {
                    setDragging(true);
                }
            }
        };

        const handleDragOut = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev - 1);
                if (dragCounter === 0) {
                    setDragging(false);
                }
            }
        };

        const handleDrop = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragging(false);
                if (e.dataTransfer.files && e.dataTransfer.files.length > 0){
                    props.handle_drop(e);
                    e.dataTransfer.clearData();
                   setDragCounter(0);
                }
            }
       };
       const enableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           if (div) {
               div.addEventListener('dragenter', handleDragIn);
               div.addEventListener('dragleave', handleDragOut);
               div.addEventListener('dragover', handleDrag);
               div.addEventListener('drop', handleDrop);
           }
       };
       const disableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           div.removeEventListener('dragenter', handleDragIn);
           div.removeEventListener('dragleave', handleDragOut);
           div.removeEventListener('dragover', handleDrag);
           div.removeEventListener('drop', handleDrop);
       };
       setDragCounter(0);
       enableDragEventListeners();
       return () => {
           // componentWillUnmount()
           disableDragEventListeners();
       };
   }, [dragCounter, props]);

   return (
       <wrapper ref={dropRef}>
           {dragging && <Overlay>{props.children}</Overlay>}
       </Wrapper>
   );
};

const DropZone = styled.div``;

export default DragAndDrop;

Body:
Issue :

const div_ref = React.useRef(null); // < --- due to null it type of div_ref becomes null

Solution :

const div_ref = React.useRef<any>(null); // <--- Provide type any
// OR
const div_ref = React.useRef<TYPE_OF_WRAPPER>(null); // <--- Provide the type of ref element

Sample demo : (With div element, you can remove the type and check, it will throw the same error )

NOTE : And I think dropRef.current; should be div_ref.current;


问:
How to open Specific View controller on Widgets/ Today Extension click
I am trying to open specific view controller on widgets click , but can not able to open it , i am able to open app using url schema but i want to open specific view controller how can i do this, here is code for open app using url schema :

@IBAction func open_app(_ sender: Any)
{ extensionContext?.open(URL(string: "open://")! ,
completionHandler: nil)
 }
 on button click i am opeing app sucessfully using url schema. but now i want to open specific view controller on that click how can i do this?

答:
In xCode 11 if you are using sceneDelegate, follow the same logic as described by Malik and Mahesh but use the following function in the SceneDelegate instead:

```<code>func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

  if let url = URLContexts.first?.url {
      //Do stuff with the url
  }

}
</code>```

(instead of application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool)

In details:

First:

Add a url scheme in your project -> info -> url Types -> add url Scheme. Here you can get started by filling the 'URL Schemes" field only (with your app name for instance).

Second:

In your extension, use the following function (called by a button for instance):

```<code>let urlString = "MyAppName://host/path"
if let url = URL(string: urlString)
{

   self?.extensionContext?.open(url, completionHandler: nil)

 }
</code>```

Third:

Implement your logic in Scene Delegate with:

```<code> func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

    if let url = URLContexts.first?.url {
      //Do stuff with the url
    }

 }
</code>```

Body:
In xCode 11 if you are using sceneDelegate, follow the same logic as described by Malik and Mahesh but use the following function in the SceneDelegate instead:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

  if let url = URLContexts.first?.url {
      //Do stuff with the url
  }

}

(instead of application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool)

In details:

First:

Add a url scheme in your project -> info -> url Types -> add url Scheme. Here you can get started by filling the 'URL Schemes" field only (with your app name for instance).

Second:

In your extension, use the following function (called by a button for instance):

let urlString = "MyAppName://host/path"
if let url = URL(string: urlString)
{

   self?.extensionContext?.open(url, completionHandler: nil)

 }

Third:

Implement your logic in Scene Delegate with:

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

    if let url = URLContexts.first?.url {
      //Do stuff with the url
    }

 }


问:
webpack-dev-server polling inside docker container - heavy CPU usage
I am running webpack-dev-server inside of a Docker container. For development purposes, I have a local directory bound to the Docker container. It's my understanding that webpack's standard "watch" abilities don't work inside Docker, or at least with volumes bound to the host machine.

But if I turn on polling (watchOptions.poll: true), the Docker container uses a lot of CPU. I can turn down polling to 1000ms or even 5000ms, but that still uses non-negligable amounts of CPU, enough so that my laptop's fans start spinning.

Are there any best practices around limiting CPU usage by a polling webpack-dev-server? Is there anything I can install inside my Linux-based Docker container? I've tried installing the latest inotify-tools, but that doesn't seem to have done the trick.

答:
for windows 10 2004 and docker desktop wsl2 backend, webpack-dev-server watch work inside docker container volumes bound to the wsl2 directory but does not work
 volumes bound to the windows directory.

I use vscode with remote-containers extension.

I open \\wsl$\Ubuntu-18.04\home\... by vscode and "reopen in container" by command-pallet.


问:
Have to click away twice from Calendar in WPF
Edit 2: Thank you all for your feedback. I solved the problem by adding this to my SelectedDatesChanged event:

Mouse.Capture(null);

When I select a date in my calendar, I want to click my "Go" button. However, I need to click the "Go" button twice: once to de-focus the calendar, and again to actually press it. The mouse leave event does not trigger on the calendar if an item is selected inside of it, and Keyboard.ClearFocus() does not de-focus it either.

Please, how can I get rid of the calendar's focus whenever I select a date?
Thank you!

Edit: Clicking the "Go" button next was merely an example; if I want to select a textbox and I have just selected a date, I would also have to click twice to enter the textbox. The main issue is that, once the calendar is interacted with, it must be clicked out of once before interacting with any other elements.

答:
Found this

Code:

```<code>public void ReleaseMouse()
{
    if (Mouse.Captured is CalendarItem) Mouse.Capture(null);
}
</code>```

XAML:

```<code><Calendar PreviewMouseUp="ReleaseMouse" />
</code>```

Source: https://quick-geek.github.io/answers/819560/index.html

Easy and seems to have no drawbacks:

Body:
Found this

Code:

public void ReleaseMouse()
{
    if (Mouse.Captured is CalendarItem) Mouse.Capture(null);
}

XAML:

<Calendar PreviewMouseUp="ReleaseMouse" />

Source: https://quick-geek.github.io/answers/819560/index.html

Easy and seems to have no drawbacks:


问:
Impala SQL in Jupyter Notebooks
Can anybody help me with the correct syntax to run multi line Impala - SQL queries in Jupyter notebooks. I have been using the approach below to run queries on a single line but have not been able to work out how to run multi line queries with indentation.

```<code>! impala-shell -q 'SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM eyesight_evaluation WHERE severity_of_sight_loss IN ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'
</code>```

Thanks!

答:
You have to use 3 single quotes for multi-line comments  </p>

```<code>'''SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM
   eyesight_evaluation WHERE severity_of_sight_loss IN
   ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'''
</code>```

Title: Impala SQL in Jupyter Notebooks

Body:
Can anybody help me with the correct syntax to run multi line Impala - SQL queries in Jupyter notebooks. I have been using the approach below to run queries on a single line but have not been able to work out how to run multi line queries with indentation.

! impala-shell -q 'SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM eyesight_evaluation WHERE severity_of_sight_loss IN ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'

Thanks!

Body:
You have to use 3 single quotes for multi-line comments

'''SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM
   eyesight_evaluation WHERE severity_of_sight_loss IN
   ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'''


问:
C# if statement interpretation
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

```<code>1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false
</code>```

答:
In line 4, b is decremented and incremented, leaving 2.

In line 5, b is decremented, then because a == --b is true, the expression short-circuits and b is not incremented, leaving 1.

In line 6 a == --b is now false.

Title: C# if statement interpretation

Body:
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false