问:
Checkboxes aren't filled in correctly when searching a list
A have a form where companies should be able to fill in information and then register to the site.

One of the things that they should be able to fill in is what category they belong to ie CRM, accounting software, ERP etc and they should be able to choose several options
in the list.

Though the list is quite long so they also have to be able to search it.
The foundation of this works but I realise that if I choose several of these categories (that are on the top of the list) and then start to search the list then (sometimes) I find that when I empty the search field some of the categories aren't clicked in anymore.

I have added an image 1 of when I have clicked in a couple of categories, then searched and then emptied the search field. Thereafter some categories are not checked but their checked value is still true.

Backend code (this is only run ones, i.e when loading the category list)

```<code>@app.route("/get_categories")
def get_categories():
    search_item = request.args.get("search_item")
    categories_query = Session.query(enjordplatformCategories ).all()

show_categories_list =[]
show_categories_dictionary=[]
i=0
for category in categories_query:
    show_categories_dictionary = {
        'i':i,
        'id' : category.id,
        'category' :category.subcategory_name_english,
        'checked':False
    }

    show_categories_list.append(show_categories_dictionary)
    i=i+1
response = json.dumps(show_categories_list)
return response
</code>```

Frontend code

HTML

```<code>    <input type="text" class="search_ruta_input" v-model="search_category"  placeholder="Search Category" v-on:keyup="search_category_func(search_category)"  >

      <div v-for="(category,idx) in this.filtered_category_list" :key="idx">
        <input type="checkbox" class="checkbox_new"  :value="category.checked" v-if="!category.checked" @click="choose_category(category)">
        <input type="checkbox" class="checkbox_filled"  :value="category.checked" v-if="category.checked" @click="choose_category(category)">
        {{category.category}} {{category.checked}}
      </div>
    </div>
  </div>
</code>```

Scripts

```<code>methods:{
        load_category(search_category){
          var self = this
          axios({
              method:'get',
              url: API_URL+ '/get_categories'+'?search_item='+search_category,
            })
            .then(function(response){
                self.category_list = response.data
            })
        },
        search_category_func(search_category){
            this.filtered_category_list =  this.category_list.filter(
              category_object =>  category_object.category.toLowerCase().includes(search_category.toLowerCase())
            )
              category => (category.category + " " + category.checked)
            ))

        },

    choose_category(category_object){
          this.category_list = this.category_list.map(category => {
            if (category.id == category_object.id){
                category.checked = category.checked === false ? true : false

            }
                return category
          })
     },

}
mounted(){
this.load_category("")

setTimeout(() => {
    this.search_category_func("")
  }, 1000);
}
</code>```

How can I resolve this?

thanks

Body:
A have a form where companies should be able to fill in information and then register to the site.

One of the things that they should be able to fill in is what category they belong to ie CRM, accounting software, ERP etc and they should be able to choose several options
in the list.

Though the list is quite long so they also have to be able to search it.
The foundation of this works but I realise that if I choose several of these categories (that are on the top of the list) and then start to search the list then (sometimes) I find that when I empty the search field some of the categories aren't clicked in anymore.

I have added an image 1 of when I have clicked in a couple of categories, then searched and then emptied the search field. Thereafter some categories are not checked but their checked value is still true.

Backend code (this is only run ones, i.e when loading the category list)

@app.route("/get_categories")
def get_categories():
    search_item = request.args.get("search_item")
    categories_query = Session.query(enjordplatformCategories ).all()

show_categories_list =[]
show_categories_dictionary=[]
i=0
for category in categories_query:
    show_categories_dictionary = {
        'i':i,
        'id' : category.id,
        'category' :category.subcategory_name_english,
        'checked':False
    }

    show_categories_list.append(show_categories_dictionary)
    i=i+1
response = json.dumps(show_categories_list)
return response

Frontend code

HTML

    <input type="text" class="search_ruta_input" v-model="search_category"  placeholder="Search Category" v-on:keyup="search_category_func(search_category)"  >

        <input type="checkbox" class="checkbox_new"  :value="category.checked" v-if="!category.checked" @click="choose_category(category)">
        <input type="checkbox" class="checkbox_filled"  :value="category.checked" v-if="category.checked" @click="choose_category(category)">
        {{category.category}} {{category.checked}}

Scripts

methods:{
        load_category(search_category){
          var self = this
          axios({
              method:'get',
              url: API_URL+ '/get_categories'+'?search_item='+search_category,
            })
            .then(function(response){
                self.category_list = response.data
            })
        },
        search_category_func(search_category){
            this.filtered_category_list =  this.category_list.filter(
              category_object =>  category_object.category.toLowerCase().includes(search_category.toLowerCase())
            )
              category => (category.category + " " + category.checked)
            ))

        },

    choose_category(category_object){
          this.category_list = this.category_list.map(category => {
            if (category.id == category_object.id){
                category.checked = category.checked === false ? true : false

            }
                return category
          })
     },

}
mounted(){
this.load_category("")

setTimeout(() => {
    this.search_category_func("")
  }, 1000);
}

How can I resolve this?

thanks


来源: stackexchange

问:
How to configure HTTPS traffic from ALB to Backend IIS Website?
I have windows Ec2 instance hosting a web site in IIS and also using ALB. I have following configuration in AWS

https://mywebsite.mydomain.com -> Application Load Balancer -> Listener (443) -> Target Group -> Windows Ec2 Instance (IIS)

I have SSL certificate configured on ALB so that all the requests from users are always on HTTPS. However, the internal traffic from ALB to Ec2 is on port 80 (HTTP)

I want to configure internal traffic (ALB -> EC2) on HTTPS using self signed certificate. I can create a self signed certificate and configure in IIS. However, I am not sure what base route the target group is using to forward the traffic to instance? Does it use private ip or machine name or something else? What should be the value for dns name for the certificate?

```<code>$dnsname= "xxxxxx"
$cert = New-SelfSignedCertificate -DnsName "$dnsname" -CertStoreLocation "cert:\LocalMachine\My"
</code>```

Here is terraform for the target group

```<code>resource "aws_lb_target_group" "https" {
  name        = "my-tg-https"
  port        = 443
  protocol    = "HTTPS"
  target_type = "instance"
  vpc_id      = var.vpc_id
  deregistration_delay = var.deregistration_delay

  health_check {
    path                = "/"
    interval            = 30
    healthy_threshold   = 2
    unhealthy_threshold = 2
    timeout             = 5
    matcher             = 200
    port                = 443
    protocol            = "HTTPS"
  }

  lifecycle {
    create_before_destroy = true
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have windows Ec2 instance hosting a web site in IIS and also using ALB. I have following configuration in AWS

https://mywebsite.mydomain.com -> Application Load Balancer -> Listener (443) -> Target Group -> Windows Ec2 Instance (IIS)

I have SSL certificate configured on ALB so that all the requests from users are always on HTTPS. However, the internal traffic from ALB to Ec2 is on port 80 (HTTP)

I want to configure internal traffic (ALB -> EC2) on HTTPS using self signed certificate. I can create a self signed certificate and configure in IIS. However, I am not sure what base route the target group is using to forward the traffic to instance? Does it use private ip or machine name or something else? What should be the value for dns name for the certificate?

$dnsname= "xxxxxx"
$cert = New-SelfSignedCertificate -DnsName "$dnsname" -CertStoreLocation "cert:\LocalMachine\My"

Here is terraform for the target group

resource "aws_lb_target_group" "https" {
  name        = "my-tg-https"
  port        = 443
  protocol    = "HTTPS"
  target_type = "instance"
  vpc_id      = var.vpc_id
  deregistration_delay = var.deregistration_delay

  health_check {
    path                = "/"
    interval            = 30
    healthy_threshold   = 2
    unhealthy_threshold = 2
    timeout             = 5
    matcher             = 200
    port                = 443
    protocol            = "HTTPS"
  }

  lifecycle {
    create_before_destroy = true
  }
}


问:
How do I hide shipping method if order amount is under minimum? Woocommerce
I need to hide or only let the customers choose shipping option delivery if the order amount is above 15. If the order amount is under 15 they should not order for delivery only for local pickup.

I tried some code i found here, but it doesnt work. it only works on cart page, if you change the delivery option on checkout page you can still order with delivery shipment method.

This is the code I found.

```<code>add_action( 'woocommerce_check_cart_items', 'wc_minimum_required_order_amount' );
function wc_minimum_required_order_amount() {

    // HERE Your settings
    $minimum_amount     = 15; // The minimum cart total amount
    $shipping_method_id = 'local_pickup'; // The targeted shipping method Id (exception)

    // Get some variables
    $total     = (float) WC()->cart->total; // Total cart amount
    $chosen_methods = (array) WC()->session->get( 'chosen_shipping_methods' ); // Chosen shipping method rate Ids (array)

    // Only when a shipping method has been chosen
    if ( ! empty($chosen_methods) ) {
        $chosen_method  = explode(':', reset($chosen_methods)); // Get the chosen shipping method Id (array)
        $chosen_method_id = reset($chosen_method); // Get the chosen shipping method Id
    }

    // If "Local pickup" shipping method is chosen, exit (no minimun is required)
    if ( isset($chosen_method_id) && $chosen_method_id === $shipping_method_id ) {
        return; // exit
    }

    // Add an error notice is cart total is less than the minimum required
    if ( $cart_total < $minimum_amount ) {
        wc_add_notice( sprintf(
            __("The minimum required order amount is %s (your current order amount is %s).", "woocommerce"), // Text message
            wc_price( $minimum_amount ),
            wc_price( $cart_total )
        ), 'error' );
    }
}
</code>```

Body:
I need to hide or only let the customers choose shipping option delivery if the order amount is above 15. If the order amount is under 15 they should not order for delivery only for local pickup.

I tried some code i found here, but it doesnt work. it only works on cart page, if you change the delivery option on checkout page you can still order with delivery shipment method.

This is the code I found.

add_action( 'woocommerce_check_cart_items', 'wc_minimum_required_order_amount' );
function wc_minimum_required_order_amount() {

    // HERE Your settings
    $minimum_amount     = 15; // The minimum cart total amount
    $shipping_method_id = 'local_pickup'; // The targeted shipping method Id (exception)

    // Get some variables
    $total     = (float) WC()->cart->total; // Total cart amount
    $chosen_methods = (array) WC()->session->get( 'chosen_shipping_methods' ); // Chosen shipping method rate Ids (array)

    // Only when a shipping method has been chosen
    if ( ! empty($chosen_methods) ) {
        $chosen_method  = explode(':', reset($chosen_methods)); // Get the chosen shipping method Id (array)
        $chosen_method_id = reset($chosen_method); // Get the chosen shipping method Id
    }

    // If "Local pickup" shipping method is chosen, exit (no minimun is required)
    if ( isset($chosen_method_id) && $chosen_method_id === $shipping_method_id ) {
        return; // exit
    }

    // Add an error notice is cart total is less than the minimum required
    if ( $cart_total < $minimum_amount ) {
        wc_add_notice( sprintf(
            __("The minimum required order amount is %s (your current order amount is %s).", "woocommerce"), // Text message
            wc_price( $minimum_amount ),
            wc_price( $cart_total )
        ), 'error' );
    }
}


问:
d3 Radial Tree and React-Flow?
Quite new with d3 but have been stuck on this for several weeks and figured I'd ask here

I've been trying to create a radial/flare tree using React-Flow but I'm having a really hard time with positioning the nodes.  I need to use React-Flow because I'd like to use custom React components instead of the standard SVG nodes from d3 since I need a higher fidelity interaction with the nodes.

Essentially I'm looking for something like this attached image but using React-Flow:
Source: https://observablehq.com/@d3/radial-tree

I don't even need the radial curve lines- it's more of a nice to have.  As long as I can get the nodes in the correct circular position, even straight lines are fine.

Would love any advice :)

Here's what I've got so far:
https://codesandbox.io/s/trusting-leavitt-b8uxi9-rf-expand-collapse-forked-fh71v8?file=/src/App.tsx:948-954

It's the collapsible tree example that the React-Flow devs gave on their website

The closest example of a radial tree using d3 using v4 or above is this: https://medium.com/analytics-vidhya/creating-a-radial-tree-using-d3-js-for-javascript-be943e23b74e

I'm trying to apply the logic that the author used in their example but the nodes aren't positioning correctly, probably due to my shallow understanding of how to use d3

There are a few other examples on here/codepen that creates a radial tree using d3 but they're all v3 or below and are focused around using SVGs as the nodes

I've also seen other radial trees from other React libraries like this: https://codesandbox.io/s/ov2jokvl1z
But they all use SVG nodes which won't work for me because I'd like to use React nodes within the graph

Title: d3 Radial Tree and React-Flow?


问:
Can "element click intercepted" error in Selenium refer to another window instead of a webElement overlapping?
I am having tests inconsistently failing because of the following error: "org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (951, 1477)".
I say inconsistently because this only happens if I go overboard with the number of parallel threads (sometimes 4+ is enough to get these errors, sometimes I need 10+ depending on what else I have running at the moment).

As you can see in the error, I am not receiving the second part which you'd usually get if the webElement in question would be obstructed by another webElement, which makes me think that somehow the element can't be clicked because it's hidden by another window... ?
What I mean by the second part is this: "Other element would receive the click: ..." - my errors do not have this part.

The weird part is that my explicit wait (set to 60 seconds) seems to be ignored, which leads me to believe that the wait condition (elementToBeClickable AND visibilityOf) is met, yet the click still doesn't work.
Again, this only happens when running multiple threads in parallel and if they are opened/closed rather slowly because of their high number, which makes the pages take 3-10 seconds to start loading its UI elements.

I am not trying to find the maximum number of threads where I don't get the error, I'm just curious as to why I receive the errors long before the wait timer reaches its end.

I tried multiple tweaks:

tried different ExpectedConditions (only elementToBeClickable, or only VisibilityOf, or both in conjunction)

scoured the internet obsessively for an answer

tried to debug with another person next to me, but to no avail

filled by code with printlines to understand the order of executions. The only interesting thing I noticed is that the threadLocalDriver.remove() function is called by my Cucumber @After hook (which runs after each scenario) before my wait condition finishes, i.e.: driver quits and is then removed from threadLocalDriver after the first print, but before the 2nd.

```<code>public void click(WebElement webElement) {
    System.out.println("starting click on thread: " + Thread.currentThread().getName());
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(waitTimer));
    wait.until(ExpectedConditions.elementToBeClickable(webElement)).click();
    System.out.println("ending click on thread: " + Thread.currentThread().getName());
}
</code>```

In fact the "ending click on thread:..." string isn't printed at all in the cases where I get that error.

Any idea what conditions I could use to make the program wait until it can actually click on the web element?

Body:
I am having tests inconsistently failing because of the following error: "org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (951, 1477)".
I say inconsistently because this only happens if I go overboard with the number of parallel threads (sometimes 4+ is enough to get these errors, sometimes I need 10+ depending on what else I have running at the moment).

As you can see in the error, I am not receiving the second part which you'd usually get if the webElement in question would be obstructed by another webElement, which makes me think that somehow the element can't be clicked because it's hidden by another window... ?
What I mean by the second part is this: "Other element would receive the click: ..." - my errors do not have this part.

The weird part is that my explicit wait (set to 60 seconds) seems to be ignored, which leads me to believe that the wait condition (elementToBeClickable AND visibilityOf) is met, yet the click still doesn't work.
Again, this only happens when running multiple threads in parallel and if they are opened/closed rather slowly because of their high number, which makes the pages take 3-10 seconds to start loading its UI elements.

I am not trying to find the maximum number of threads where I don't get the error, I'm just curious as to why I receive the errors long before the wait timer reaches its end.

I tried multiple tweaks:

tried different ExpectedConditions (only elementToBeClickable, or only VisibilityOf, or both in conjunction)

scoured the internet obsessively for an answer

tried to debug with another person next to me, but to no avail

filled by code with printlines to understand the order of executions. The only interesting thing I noticed is that the threadLocalDriver.remove() function is called by my Cucumber @After hook (which runs after each scenario) before my wait condition finishes, i.e.: driver quits and is then removed from threadLocalDriver after the first print, but before the 2nd.

public void click(WebElement webElement) {
    System.out.println("starting click on thread: " + Thread.currentThread().getName());
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(waitTimer));
    wait.until(ExpectedConditions.elementToBeClickable(webElement)).click();
    System.out.println("ending click on thread: " + Thread.currentThread().getName());
}

In fact the "ending click on thread:..." string isn't printed at all in the cases where I get that error.

Any idea what conditions I could use to make the program wait until it can actually click on the web element?


问:
Angular Typescript correct way to convert string to date irrespective of timezone?
I am using Angular version 10 and has typescript 3.9 .

I am trying to convert the string (only date, no time) to Date object and it is adding the 1 day to it. I am not using "now", just passing the actual date string value (past values too). For example trying this on playground (today is 7th dec not 31st, so "now" or current time does not matter):

```<code>const anExampleVariable = "Hello World"
console.log(anExampleVariable)

let valDate = null;
const dateStr = "2022-11-31"
var parts = dateStr.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
valDate = new Date(parts[0], parts[1]-1, parts[2])
console.log(valDate)
</code>```

The output us as follows:

```<code>[LOG]: "Hello World"
[LOG]: Date: "2022-12-01T05:00:00.000Z"
</code>```

Why is it adding one day to the string passed?
How do I "simply" convert the date(only) string to Date object?

Body:
I am using Angular version 10 and has typescript 3.9 .

I am trying to convert the string (only date, no time) to Date object and it is adding the 1 day to it. I am not using "now", just passing the actual date string value (past values too). For example trying this on playground (today is 7th dec not 31st, so "now" or current time does not matter):

const anExampleVariable = "Hello World"
console.log(anExampleVariable)

let valDate = null;
const dateStr = "2022-11-31"
var parts = dateStr.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
valDate = new Date(parts[0], parts[1]-1, parts[2])
console.log(valDate)

The output us as follows:

[LOG]: "Hello World"
[LOG]: Date: "2022-12-01T05:00:00.000Z"

Why is it adding one day to the string passed?
How do I "simply" convert the date(only) string to Date object?


问:
Using enum as one of the key pair for unordered_map using boost's hash_value
I want to have a pair as a key for an unordered_map which by default doesn't provide such a hash hence I am replicating the boost hash APIs but running into some issues.

This is how I instantiated a map using a pair

```<code>using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;
</code>```

And this is how it's being used

```<code>void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}
</code>```

with Values being an enum, I get an error saying:

could not convert 'val' from 'Values' to 'std::__hash_enum<Values, true>'.

Does that mean T can't be of enum type? Sample code

```<code>template <class T>
std::size_t hash_value(T val)
{
    return std::hash<T>(val);
}

template <class T>
inline void hash_combine( std::size_t& seed, T const& v)
{
    custom_hash<T>()(v);
}

template <class A, class B>
std::size_t hash_value(std::pair<A, B> const& v)
{
  std::size_t seed = 0;

  hash_combine(seed, v.first);
  hash_combine(seed, v.second);

  return seed;
}

template <class T> struct custom_hash
{
    typedef T argument_type;
    typedef std::size_t result_type;

    std::size_t operator()(T const& val) const
    {
        return hash_value(val);
    }
};

enum class Values
{
    one
};

using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;

void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}
</code>```

Body:
I want to have a pair as a key for an unordered_map which by default doesn't provide such a hash hence I am replicating the boost hash APIs but running into some issues.

This is how I instantiated a map using a pair

using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;

And this is how it's being used

void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}

with Values being an enum, I get an error saying:

could not convert 'val' from 'Values' to 'std::__hash_enum<Values, true>'.

Does that mean T can't be of enum type? Sample code

template <class T>
std::size_t hash_value(T val)
{
    return std::hash<T>(val);
}

template <class T>
inline void hash_combine( std::size_t& seed, T const& v)
{
    custom_hash<T>()(v);
}

template <class A, class B>
std::size_t hash_value(std::pair const& v)
{
  std::size_t seed = 0;

  hash_combine(seed, v.first);
  hash_combine(seed, v.second);

  return seed;
}

template <class T> struct custom_hash
{
    typedef T argument_type;
    typedef std::size_t result_type;

    std::size_t operator()(T const& val) const
    {
        return hash_value(val);
    }
};

enum class Values
{
    one
};

using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;

void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}


问:
npm ERR! code ERESOLVE | npm ERR! ERESOLVE could not resolve
I've the steps on these two threads, but to no avail.

ERESOLVE unable to resolve dependency tree while installing a pacakge

Unable to resolve dependency tree error when installing npm packages

It's still giving me the same error on Heroku:

```<code>-----> Installing dependencies
       Installing node modules
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE could not resolve
       npm ERR!
       npm ERR! While resolving: @solana/wallet-adapter-material-ui@0.13.1
       npm ERR! Found: @types/react@18.0.26
       npm ERR! node_modules/@types/react
       npm ERR!   dev @types/react@"^18.0.17" from the root project
       npm ERR!   @types/react@"*" from @types/hoist-non-react-statics@3.3.1
       npm ERR!   node_modules/@types/hoist-non-react-statics
       npm ERR!     @types/hoist-non-react-statics@"*" from @types/styled-components@5.1.26
       npm ERR!     node_modules/@types/styled-components
       npm ERR!       dev @types/styled-components@"^5.1.15" from the root project
       npm ERR!   3 more (@types/react-slick, ...)
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer @material-ui/core@"^4.12.1" from @solana/wallet-adapter-material-ui@0.13.1
       npm ERR! node_modules/@solana/wallet-adapter-material-ui
       npm ERR!   @solana/wallet-adapter-material-ui@"^0.13.1" from the root project
       npm ERR!
       npm ERR! Conflicting peer dependency: @types/react@17.0.52
       npm ERR! node_modules/@types/react
       npm ERR!   peerOptional @types/react@"^16.8.6 || ^17.0.0" from @material-ui/core@4.12.4
       npm ERR!   node_modules/@material-ui/core
       npm ERR!     peer @material-ui/core@"^4.12.1" from @solana/wallet-adapter-material-ui@0.13.1
       npm ERR!     node_modules/@solana/wallet-adapter-material-ui
       npm ERR!       @solana/wallet-adapter-material-ui@"^0.13.1" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.jlWS6/eresolve-report.txt for a full report.
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.jlWS6/_logs/2022-12-07T22_37_42_614Z-debug-0.log
</code>```

Here's by package.json:

```<code>{
  "name": "qtbotz-landing",
  "version": "0.2.0",
  "private": true,
  "scripts": {
    "lint": "next lint",
    "lint:es": "eslint --ext .ts,.tsx .",
    "lint:fix": "eslint --fix --ext .ts,.tsx .",
    "dev": "open http://localhost:1337 && next dev -p 1337",
    "start": "next start",
    "build": "next build",
    "clear-all": "rm -rf .next _static node_modules",
    "re-start": "rm -rf .next _static node_modules && yarn install && yarn dev",
    "re-build": "rm -rf .next _static node_modules && yarn install && yarn build",
    "analyze": "ANALYZE=true next build"
  },
  "dependencies": {
    "@emotion/react": "^11.10.0",
    "@next/bundle-analyzer": "^12.0.2",
    "@next/eslint-plugin-next": "^12.0.4",
    "@project-serum/anchor": "^0.18.2",
    "@solana/spl-token": "^0.1.8",
    "@solana/wallet-adapter-base": "^0.7.0",
    "@solana/wallet-adapter-material-ui": "^0.13.1",
    "@solana/wallet-adapter-react": "^0.13.1",
    "@solana/wallet-adapter-react-ui": "^0.6.1",
    "@solana/wallet-adapter-wallets": "^0.11.3",
    "@solana/web3.js": "^1.27.0",
    "autoprefixer": "^10.4.8",
    "axios": "^0.24.0",
    "classnames": "^2.3.1",
    "cross-env": "^7.0.3",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "locomotive-scroll": "^4.1.4",
    "lodash": "^4.17.21",
    "moment": "^2.29.1",
    "next": "^12.0.2",
    "next-compose-plugins": "^2.2.1",
    "next-seo": "^4.28.1",
    "next-transpile-modules": "^9.0.0",
    "react": "^17.0.2",
    "react-accessible-accordion": "^4.0.0",
    "react-awesome-reveal": "^4.0.0",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-locomotive-scroll": "^0.2.2",
    "react-marquee-slider": "^1.1.5",
    "react-slick": "^0.29.0",
    "react-star-sky": "^1.0.3",
    "react-starfield-animation": "^1.0.1",
    "shooting-stars": "^0.0.6",
    "slick-carousel": "^1.8.1",
    "smooth-scrollbar": "^8.7.5",
    "smooth-scrollbar-react": "^2.3.0",
    "stream": "^0.0.2",
    "styled-components": "^5.3.5",
    "styled-jsx-plugin-postcss": "^4.0.1",
    "tailwindcss": "^2.2.19"
  },
  "devDependencies": {
    "@types/jsonwebtoken": "^8.5.6",
    "@types/node": "^16.11.9",
    "@types/react": "^18.0.17",
    "@types/react-slick": "^0.23.10",
    "@types/react-vertical-timeline-component": "^3.3.1",
    "@types/styled-components": "^5.1.15",
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "eslint": "<8.0.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-airbnb-typescript": "^16.0.0",
    "eslint-config-next": "^12.0.2",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.27.1",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-unused-imports": "^2.0.0",
    "lint-staged": "^12.0.3",
    "npm-run-all": "^4.1.5",
    "postcss": "^8.3.11",
    "prettier": "^2.4.1",
    "rimraf": "^3.0.2",
    "typescript": "^4.5.2"
  },
  "license": "ISC",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I've attempted to fix the problem by removing the node modules and the package.json, but every time I push to Heroku, the problem still arises.

It might be peer dependency issue, or an NPM issue but I wouldn't know where to start.

Thanks again, and let me know if you have any questions.

Body:
I've the steps on these two threads, but to no avail.

ERESOLVE unable to resolve dependency tree while installing a pacakge

Unable to resolve dependency tree error when installing npm packages

It's still giving me the same error on Heroku:

-----> Installing dependencies
       Installing node modules
       npm ERR! code ERESOLVE
       npm ERR! ERESOLVE could not resolve
       npm ERR!
       npm ERR! While resolving: @solana/wallet-adapter-material-ui@0.13.1
       npm ERR! Found: @types/react@18.0.26
       npm ERR! node_modules/@types/react
       npm ERR!   dev @types/react@"^18.0.17" from the root project
       npm ERR!   @types/react@"*" from @types/hoist-non-react-statics@3.3.1
       npm ERR!   node_modules/@types/hoist-non-react-statics
       npm ERR!     @types/hoist-non-react-statics@"*" from @types/styled-components@5.1.26
       npm ERR!     node_modules/@types/styled-components
       npm ERR!       dev @types/styled-components@"^5.1.15" from the root project
       npm ERR!   3 more (@types/react-slick, ...)
       npm ERR!
       npm ERR! Could not resolve dependency:
       npm ERR! peer @material-ui/core@"^4.12.1" from @solana/wallet-adapter-material-ui@0.13.1
       npm ERR! node_modules/@solana/wallet-adapter-material-ui
       npm ERR!   @solana/wallet-adapter-material-ui@"^0.13.1" from the root project
       npm ERR!
       npm ERR! Conflicting peer dependency: @types/react@17.0.52
       npm ERR! node_modules/@types/react
       npm ERR!   peerOptional @types/react@"^16.8.6 || ^17.0.0" from @material-ui/core@4.12.4
       npm ERR!   node_modules/@material-ui/core
       npm ERR!     peer @material-ui/core@"^4.12.1" from @solana/wallet-adapter-material-ui@0.13.1
       npm ERR!     node_modules/@solana/wallet-adapter-material-ui
       npm ERR!       @solana/wallet-adapter-material-ui@"^0.13.1" from the root project
       npm ERR!
       npm ERR! Fix the upstream dependency conflict, or retry
       npm ERR! this command with --force, or --legacy-peer-deps
       npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
       npm ERR!
       npm ERR! See /tmp/npmcache.jlWS6/eresolve-report.txt for a full report.
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.jlWS6/_logs/2022-12-07T22_37_42_614Z-debug-0.log

Here's by package.json:

{
  "name": "qtbotz-landing",
  "version": "0.2.0",
  "private": true,
  "scripts": {
    "lint": "next lint",
    "lint:es": "eslint --ext .ts,.tsx .",
    "lint:fix": "eslint --fix --ext .ts,.tsx .",
    "dev": "open http://localhost:1337 && next dev -p 1337",
    "start": "next start",
    "build": "next build",
    "clear-all": "rm -rf .next _static node_modules",
    "re-start": "rm -rf .next _static node_modules && yarn install && yarn dev",
    "re-build": "rm -rf .next _static node_modules && yarn install && yarn build",
    "analyze": "ANALYZE=true next build"
  },
  "dependencies": {
    "@emotion/react": "^11.10.0",
    "@next/bundle-analyzer": "^12.0.2",
    "@next/eslint-plugin-next": "^12.0.4",
    "@project-serum/anchor": "^0.18.2",
    "@solana/spl-token": "^0.1.8",
    "@solana/wallet-adapter-base": "^0.7.0",
    "@solana/wallet-adapter-material-ui": "^0.13.1",
    "@solana/wallet-adapter-react": "^0.13.1",
    "@solana/wallet-adapter-react-ui": "^0.6.1",
    "@solana/wallet-adapter-wallets": "^0.11.3",
    "@solana/web3.js": "^1.27.0",
    "autoprefixer": "^10.4.8",
    "axios": "^0.24.0",
    "classnames": "^2.3.1",
    "cross-env": "^7.0.3",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "locomotive-scroll": "^4.1.4",
    "lodash": "^4.17.21",
    "moment": "^2.29.1",
    "next": "^12.0.2",
    "next-compose-plugins": "^2.2.1",
    "next-seo": "^4.28.1",
    "next-transpile-modules": "^9.0.0",
    "react": "^17.0.2",
    "react-accessible-accordion": "^4.0.0",
    "react-awesome-reveal": "^4.0.0",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-locomotive-scroll": "^0.2.2",
    "react-marquee-slider": "^1.1.5",
    "react-slick": "^0.29.0",
    "react-star-sky": "^1.0.3",
    "react-starfield-animation": "^1.0.1",
    "shooting-stars": "^0.0.6",
    "slick-carousel": "^1.8.1",
    "smooth-scrollbar": "^8.7.5",
    "smooth-scrollbar-react": "^2.3.0",
    "stream": "^0.0.2",
    "styled-components": "^5.3.5",
    "styled-jsx-plugin-postcss": "^4.0.1",
    "tailwindcss": "^2.2.19"
  },
  "devDependencies": {
    "@types/jsonwebtoken": "^8.5.6",
    "@types/node": "^16.11.9",
    "@types/react": "^18.0.17",
    "@types/react-slick": "^0.23.10",
    "@types/react-vertical-timeline-component": "^3.3.1",
    "@types/styled-components": "^5.1.15",
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "eslint": "<8.0.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-airbnb-typescript": "^16.0.0",
    "eslint-config-next": "^12.0.2",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.27.1",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-unused-imports": "^2.0.0",
    "lint-staged": "^12.0.3",
    "npm-run-all": "^4.1.5",
    "postcss": "^8.3.11",
    "prettier": "^2.4.1",
    "rimraf": "^3.0.2",
    "typescript": "^4.5.2"
  },
  "license": "ISC",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I've attempted to fix the problem by removing the node modules and the package.json, but every time I push to Heroku, the problem still arises.

It might be peer dependency issue, or an NPM issue but I wouldn't know where to start.

Thanks again, and let me know if you have any questions.


问:
Cypress test runner intermittent ECONNREFUSED 127.0.0.1:4200
I'm having intermittent issues running some automated e2e tests written in Cypress. Apparently I'm the only one having this issue so it might be isolated to my laptop. The strange thing is it happens intermittently.

When I run the tests and cypress tries to browse to our app I get the following error:

`CypressError
cy.visit() failed trying to load:

http://localhost:4200/

We attempted to make an http request to this URL but the request failed without a response.

We received this error at the network level:

Error: connect ECONNREFUSED 127.0.0.1:4200

Common situations why this would fail:

you don't have internet access

you forgot to run / boot your web server

your web server isn't accessible

you have weird network configuration settings on your computer`

If I open a new tab in the instance of Chrome that is controlled by Cypress I also get the same error.

If I open a standard instance of Chrome (not controlled by Cypress) the page loads fine.

The really weird thing is I can put money if I try again in a couple of hours it will just start working.

Anyone got any hunches on this one because I'm clueless or not sure how to debug.


问:
Why is running raw SQL in Rails via ActiveRecord::Base.connection.execute taking 10X longer than same SQL run in client or stored procedure?
I'm working in Rails and executing raw SQL to create and manage a table of temporary data for a nightly batch process. I'm planning on getting all the raw statements of the process into Stored Procedures eventually, but I'm just using ActiveRecord::Base.connection.execute to save some time during development and testing. Or so I thought.

This SQL statement in my client (DBeaver) runs in under 5 seconds:

```<code>UPDATE tmp_reporting_sales_ia
SET reporting_license_type = NULL,
    reporting_residency = 'N'
;
# Updated Rows  1304030
</code>```

(Note: if I RESET QUERY CACHE; before running the statement, same results)

However, if I run that same statement via the ActiveRecord connection, it takes over 50 seconds.

```<code>ActiveRecord::Base.connection.execute("UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N';")
D, [2022-12-07T22:16:13.231127 #7] DEBUG -- :    (51585.2ms)  UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N';
=> nil
</code>```

If I do create a stored procedure for this exact statement and then call that via the ActiveRecord connection, it again runs in under 5 seconds.

```<code>irb(main):024:0> ActiveRecord::Base.connection.execute("CALL reset_reporting_sales();")
D, [2022-12-07T22:25:06.252457 #7] DEBUG -- :    (4297.1ms)  CALL reset_reporting_sales();
=> nil
</code>```

This is just one basic example, but I'm seeing the same issue with many other statements of higher complexity. I'd really rather not have to deal with the stored procedures until everything is nailed down.

Can anyone explain what Rails overhead is causing the execution of this and other statements via the ActiveRecord connection to take 10 times as long?

Body:
I'm working in Rails and executing raw SQL to create and manage a table of temporary data for a nightly batch process. I'm planning on getting all the raw statements of the process into Stored Procedures eventually, but I'm just using ActiveRecord::Base.connection.execute to save some time during development and testing. Or so I thought.

This SQL statement in my client (DBeaver) runs in under 5 seconds:

UPDATE tmp_reporting_sales_ia
SET reporting_license_type = NULL,
    reporting_residency = 'N'
;
# Updated Rows  1304030

(Note: if I RESET QUERY CACHE; before running the statement, same results)

However, if I run that same statement via the ActiveRecord connection, it takes over 50 seconds.

ActiveRecord::Base.connection.execute("UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N';")
D, [2022-12-07T22:16:13.231127 #7] DEBUG -- :    (51585.2ms)  UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N';
=> nil

If I do create a stored procedure for this exact statement and then call that via the ActiveRecord connection, it again runs in under 5 seconds.

irb(main):024:0> ActiveRecord::Base.connection.execute("CALL reset_reporting_sales();")
D, [2022-12-07T22:25:06.252457 #7] DEBUG -- :    (4297.1ms)  CALL reset_reporting_sales();
=> nil

This is just one basic example, but I'm seeing the same issue with many other statements of higher complexity. I'd really rather not have to deal with the stored procedures until everything is nailed down.

Can anyone explain what Rails overhead is causing the execution of this and other statements via the ActiveRecord connection to take 10 times as long?


问:
Spring Data Jpa: how to filter @OneToMany child entities in the specification
I have 2 entities.

Parent entity:

```<code>
@Entity
@Getter
@Setter
public class Room {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int number;

@OneToMany(mappedBy = "room", cascade = CascadeType.ALL)
private List<BookingRequest> bookingRequests;
}
</code>```

Child entity:

```<code>
@Entity
@Getter
@Setter
public class BookingRequest {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private LocalDateTime startTime;
private LocalDateTime endTime;

@ManyToOne
@JoinColumn(name = "room_id", referencedColumnName = "id")
private Room room;
}
</code>```

What I do:

```<code>@Service
@RequiredArgsConstructor
public class RoomService {

    private final RoomRepository roomRepository;

    // method call is inside of @Transactional
    public List<Room> findWithBookingRequestsAfter(LocalDateTime after) {
        Specification<Room> spec = Specification.where(hasBookingsAfter(after));
        return roomRepository.findAll(spec);
    }

    private static Specification<Agent> hasBookingsAfter(LocalDateTime after) {
        return (root,criteriaQuery, criteriaBuilder) -> {
            Join<Room, BookingRequest>join = root("bookingRequests", JoinType.LEFT);
            join.on(criteriaBuilder.greaterThanOrEqualTo(join.get("startTime"), after));

            return criteriaBuilder.conjunction();
        } ;

    }

}
</code>```

The RoomRepository is a simple interface which implements JpaRepository and JpaExecutor for Room.

As result - hibernate generates LEFT OUTER JOIN, with filtering bookingRequests during the 'on' clause.

But anyway, when I am debugging my application - hibernate does initialisation of the lazy collection.

In simple word it creates 1 select request for lazy loaded collections. The query is not filtered, it just joins all rooms and booking requests. As result - my query returns all booking requests which are linked to the Room. Not a filtered ones.

I have tried to use both @Query from JPA repository and specification functionality. But anyway, Hibernate does initialization of the lazy loaded fieds.

Body:
I have 2 entities.

Parent entity:

@Entity
@Getter
@Setter
public class Room {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int number;

@OneToMany(mappedBy = "room", cascade = CascadeType.ALL)
private List<BookingRequest> bookingRequests;
}

Child entity:

@Entity
@Getter
@Setter
public class BookingRequest {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private LocalDateTime startTime;
private LocalDateTime endTime;

@ManyToOne
@JoinColumn(name = "room_id", referencedColumnName = "id")
private Room room;
}

What I do:

@Service
@RequiredArgsConstructor
public class RoomService {

    private final RoomRepository roomRepository;

    // method call is inside of @Transactional
    public List<Room> findWithBookingRequestsAfter(LocalDateTime after) {
        Specification<Room> spec = Specification.where(hasBookingsAfter(after));
        return roomRepository.findAll(spec);
    }

    private static Specification<Agent> hasBookingsAfter(LocalDateTime after) {
        return (root,criteriaQuery, criteriaBuilder) -> {
            Join<Room, BookingRequest>join = root("bookingRequests", JoinType.LEFT);
            join.on(criteriaBuilder.greaterThanOrEqualTo(join.get("startTime"), after));

            return criteriaBuilder.conjunction();
        } ;

    }

}

The RoomRepository is a simple interface which implements JpaRepository and JpaExecutor for Room.

As result - hibernate generates LEFT OUTER JOIN, with filtering bookingRequests during the 'on' clause.

But anyway, when I am debugging my application - hibernate does initialisation of the lazy collection.

In simple word it creates 1 select request for lazy loaded collections. The query is not filtered, it just joins all rooms and booking requests. As result - my query returns all booking requests which are linked to the Room. Not a filtered ones.

I have tried to use both @Query from JPA repository and specification functionality. But anyway, Hibernate does initialization of the lazy loaded fieds.


问:
python script in spss extension .spe
I have a python file to run in spss but I get the following error

prints the data diagonally the program includes a .spe file

link to files on drive

what happens I make changes in both the .py and the .spe file and no change happens when uploading it to spss.

The code in python is the following

```<code>
from __future__ import division
from extension import Syntax, Template, processcmd
import spssaux, spss, spssdata, operator

helptext = """PIM TOT_EVAL=Tot_eval_1 TO Tot_eval_2
EMO_HARMONY= EMO_HARM_1 to EMO_HARM_2
/OPTIONS
         PIM_NAME = název [PIMINX]
/HELP - zobrazí pouze nápovědu.

příklady:
PIM TOT_EVAL= Q4_1 TO  Q4_25 EMO_HARMONY= Q5_1 to Q5_25.

PIM TOT_EVAL= Q4_1 TO  Q4_25 EMO_HARMONY= Q5_1 to Q5_25 /OPTIONS PIM_NAME=PIMindex.
"""

#enable localization
global _
try:
    _("---")
except:
    def _(msg):
        return msg

def Run(args):
    args = args[args.keys()[0]]

    oobj = Syntax([
        Template(kwd="TOT_EVAL",subc="",ktype="existingvarlist",var="evaluation",islist=True),
        Template(kwd="EMO_HARMONY",subc="",ktype="existingvarlist",var="harmony",islist=True),
        Template("PIM_NAME", subc="OPTIONS", ktype="varname", var="pimname"),
        Template("HELP", subc="", ktype="bool")])

    if args.has_key("HELP"):
        print helptext
    else:
        processcmd(oobj, args, pim)

def pim(evaluation,harmony,pimname="PIM"):
 vdict=spssaux.VariableDict(caseless=True)
 p_eval = vdict.expand(spssaux._buildvarlist(evaluation))
 p_harm = vdict.expand(spssaux._buildvarlist(harmony))

 # EXITUJOU VSECHNY PROMENNE ?
 for var in p_eval:
  checkVariables(vdict,var)
 for var in p_harm:
  checkVariables(vdict,var)

 # kontrola na stejnou délku seznamů
 if len(p_eval)<>len(p_harm):
  raise ValueError(_("Dva zadané seznamy proměnných nejsou stejně dlouhé"))

 # rekod sys proměnných na 0
 job='recode '
 for val in p_eval:
  job+= val + ' '
 for val in p_harm:
  job+= val + ' '

 job+= ' (sys=0). \n EXECUTE.'

 spss.Submit(job)

 data = spssdata.Spssdata(accessType='r',names=False,convertUserMissing=False)
 # PREVEDE NAZVY PROMENNYCH NA MALA PISMENA
 evaluation = [item.lower() for item in p_eval]
 harmony = [item.lower() for item in p_harm]
 data_varnames = [item.lower() for item in data.varnames()]

 data_arr = []
 res_values = []
 tiskni = 0
 poznamky = 'Upozornění: \n'

 # načtu si součet hodnocení a harmonie do vektoru pro každý řádek
 row_i = 0
 for row in data:
  p_eval=[]
  p_harm=[]
  p_evha=[]
  checkEVA=[]
  checkEMO=[]
  for var in evaluation:
   p_eval.append(row[data_varnames.index(var)])
  for var in harmony:
   p_harm.append(row[data_varnames.index(var)])
  for i in range(len(p_eval)):
   checkEVA=checkValEVA(p_eval[i],i,row_i)
   checkEMO=checkValEMO(p_harm[i],i,row_i)
   if checkEVA[0] >0:
    poznamky += checkEVA[1]
   if checkEMO[0] >0:
    poznamky += checkEMO[1]
   if (checkEVA[0] >0) or (checkEMO[0] >0):
    tiskni=1
   p_evha.append(p_eval[i]+p_harm[i])
  data_arr.append(p_evha)
  row_i+=1
 data.CClose()

 if tiskni==1:
  print poznamky

 data = spssdata.Spssdata(accessType='w',names=False,convertUserMissing=False)
 for i in range(len(evaluation)):
  data.append(spssdata.vdef(pimname+'_'+str(i+1),vlabel='PIM'+'_'+str(i+1),vfmt=["F",4,2]))
 data.commitdict()
 row_i = 0
 for row in data:
  res_values = pim_count(data_arr[row_i])
  for i in range(len(res_values)):
   data.setvalue(pimname+'_'+str(i+1),res_values[i])
   data.CommitCase()
  row_i += 1
 data.CClose()

def checkVariables(vardict,varname):
    try:
        return vardict[varname]
    except:
        raise ValueError(_("Promenna '"+varname+"' neexistuje"))

def checkValEVA(VAL_EVA,zni,rdi):
 xtisk=0
 zprava=''
 if (VAL_EVA <0) or (VAL_EVA > 10):
  xtisk=1
  zprava = 'v proměnné CELKOVÉ HODNOCENÍ značky ' + str(zni+1) + ' je na řádku ' + str(rdi+1) + ' hodnota mimo rozsah 0 až 10!!! \n'
 return [xtisk,zprava]

def checkValEMO(VAL_EMO,zni,rdi):
 xtisk=0
 zprava=''
 if (VAL_EMO <0) or (VAL_EMO > 7):
  xtisk=1
  zprava = 'v proměnné EMOCIONÁLNÍ SOUZNĚNÍ značky ' + str(zni+1) + ' je na řádku ' + str(rdi+1) + ' hodnota mimo rozsah 0 až 7!!! \n'
 return [xtisk,zprava]

def pim_count(data_arr1):
    #data_arr_s=sorted(data_arr1)
    dict_orig={}
    dict_ord={}
    for i in range(len(data_arr1)):
        dict_orig[i]=data_arr1[i]
    #dicsorted=sorted(dict_orig.items(),key=operator.itemgetter(1),reverse=True)
    dicsorted=sorted(dict_orig.items(),key=operator.itemgetter(1))

    i=0
    while i < len(dicsorted):
        j=0
        si=0
        ordix=0
        while (i+j <len(dicsorted)) and (dicsorted[i][1]==dicsorted[i+j][1]):
            si+=(i+j)
            j+=1
        ordix=si/j
        j=0
        while (i+j <len(dicsorted)) and (dicsorted[i][1]==dicsorted[i+j][1]):
            dict_ord[dicsorted[i+j][0]]=ordix+1
            j+=1
        i=i+j

    dic_org_sort=sorted(dict_orig.items(),key=operator.itemgetter(0))
    dic_ord_sort=sorted(dict_ord.items(),key=operator.itemgetter(0))
    pims=[]
    spimval=0
    for i in range(len(data_arr1)):
        pimval=dic_org_sort[i][1]/(len(data_arr1)-dic_ord_sort[i][1]+1)
        pims.append(pimval)
        spimval+=pimval
    if spimval==0:
        spimval=1
    return [item/spimval*100 for item in pims]

</code>```

I hope your help

Title: python script in spss extension .spe

Body:
I have a python file to run in spss but I get the following error

prints the data diagonally the program includes a .spe file

link to files on drive

what happens I make changes in both the .py and the .spe file and no change happens when uploading it to spss.

The code in python is the following

from __future__ import division
from extension import Syntax, Template, processcmd
import spssaux, spss, spssdata, operator

helptext = """PIM TOT_EVAL=Tot_eval_1 TO Tot_eval_2
EMO_HARMONY= EMO_HARM_1 to EMO_HARM_2
/OPTIONS
         PIM_NAME = název [PIMINX]
/HELP - zobrazí pouze nápovědu.

příklady:
PIM TOT_EVAL= Q4_1 TO  Q4_25 EMO_HARMONY= Q5_1 to Q5_25.

PIM TOT_EVAL= Q4_1 TO  Q4_25 EMO_HARMONY= Q5_1 to Q5_25 /OPTIONS PIM_NAME=PIMindex.
"""

#enable localization
global _
try:
    _("---")
except:
    def _(msg):
        return msg

def Run(args):
    args = args[args.keys()[0]]

    oobj = Syntax([
        Template(kwd="TOT_EVAL",subc="",ktype="existingvarlist",var="evaluation",islist=True),
        Template(kwd="EMO_HARMONY",subc="",ktype="existingvarlist",var="harmony",islist=True),
        Template("PIM_NAME", subc="OPTIONS", ktype="varname", var="pimname"),
        Template("HELP", subc="", ktype="bool")])

    if args.has_key("HELP"):
        print helptext
    else:
        processcmd(oobj, args, pim)

def pim(evaluation,harmony,pimname="PIM"):
 vdict=spssaux.VariableDict(caseless=True)
 p_eval = vdict.expand(spssaux._buildvarlist(evaluation))
 p_harm = vdict.expand(spssaux._buildvarlist(harmony))

 # EXITUJOU VSECHNY PROMENNE ?
 for var in p_eval:
  checkVariables(vdict,var)
 for var in p_harm:
  checkVariables(vdict,var)

 # kontrola na stejnou délku seznamů
 if len(p_eval)<>len(p_harm):
  raise ValueError(_("Dva zadané seznamy proměnných nejsou stejně dlouhé"))

 # rekod sys proměnných na 0
 job='recode '
 for val in p_eval:
  job+= val + ' '
 for val in p_harm:
  job+= val + ' '

 job+= ' (sys=0). \n EXECUTE.'

 spss.Submit(job)

 data = spssdata.Spssdata(accessType='r',names=False,convertUserMissing=False)
 # PREVEDE NAZVY PROMENNYCH NA MALA PISMENA
 evaluation = [item.lower() for item in p_eval]
 harmony = [item.lower() for item in p_harm]
 data_varnames = [item.lower() for item in data.varnames()]

 data_arr = []
 res_values = []
 tiskni = 0
 poznamky = 'Upozornění: \n'

 # načtu si součet hodnocení a harmonie do vektoru pro každý řádek
 row_i = 0
 for row in data:
  p_eval=[]
  p_harm=[]
  p_evha=[]
  checkEVA=[]
  checkEMO=[]
  for var in evaluation:
   p_eval.append(row[data_varnames.index(var)])
  for var in harmony:
   p_harm.append(row[data_varnames.index(var)])
  for i in range(len(p_eval)):
   checkEVA=checkValEVA(p_eval[i],i,row_i)
   checkEMO=checkValEMO(p_harm[i],i,row_i)
   if checkEVA[0] >0:
    poznamky += checkEVA[1]
   if checkEMO[0] >0:
    poznamky += checkEMO[1]
   if (checkEVA[0] >0) or (checkEMO[0] >0):
    tiskni=1
   p_evha.append(p_eval[i]+p_harm[i])
  data_arr.append(p_evha)
  row_i+=1
 data.CClose()

 if tiskni==1:
  print poznamky

 data = spssdata.Spssdata(accessType='w',names=False,convertUserMissing=False)
 for i in range(len(evaluation)):
  data.append(spssdata.vdef(pimname+'_'+str(i+1),vlabel='PIM'+'_'+str(i+1),vfmt=["F",4,2]))
 data.commitdict()
 row_i = 0
 for row in data:
  res_values = pim_count(data_arr[row_i])
  for i in range(len(res_values)):
   data.setvalue(pimname+'_'+str(i+1),res_values[i])
   data.CommitCase()
  row_i += 1
 data.CClose()

def checkVariables(vardict,varname):
    try:
        return vardict[varname]
    except:
        raise ValueError(_("Promenna '"+varname+"' neexistuje"))

def checkValEVA(VAL_EVA,zni,rdi):
 xtisk=0
 zprava=''
 if (VAL_EVA <0) or (VAL_EVA > 10):
  xtisk=1
  zprava = 'v proměnné CELKOVÉ HODNOCENÍ značky ' + str(zni+1) + ' je na řádku ' + str(rdi+1) + ' hodnota mimo rozsah 0 až 10!!! \n'
 return [xtisk,zprava]

def checkValEMO(VAL_EMO,zni,rdi):
 xtisk=0
 zprava=''
 if (VAL_EMO <0) or (VAL_EMO > 7):
  xtisk=1
  zprava = 'v proměnné EMOCIONÁLNÍ SOUZNĚNÍ značky ' + str(zni+1) + ' je na řádku ' + str(rdi+1) + ' hodnota mimo rozsah 0 až 7!!! \n'
 return [xtisk,zprava]

def pim_count(data_arr1):
    #data_arr_s=sorted(data_arr1)
    dict_orig={}
    dict_ord={}
    for i in range(len(data_arr1)):
        dict_orig[i]=data_arr1[i]
    #dicsorted=sorted(dict_orig.items(),key=operator.itemgetter(1),reverse=True)
    dicsorted=sorted(dict_orig.items(),key=operator.itemgetter(1))

    i=0
    while i < len(dicsorted):
        j=0
        si=0
        ordix=0
        while (i+j <len(dicsorted)) and (dicsorted[i][1]==dicsorted[i+j][1]):
            si+=(i+j)
            j+=1
        ordix=si/j
        j=0
        while (i+j <len(dicsorted)) and (dicsorted[i][1]==dicsorted[i+j][1]):
            dict_ord[dicsorted[i+j][0]]=ordix+1
            j+=1
        i=i+j

    dic_org_sort=sorted(dict_orig.items(),key=operator.itemgetter(0))
    dic_ord_sort=sorted(dict_ord.items(),key=operator.itemgetter(0))
    pims=[]
    spimval=0
    for i in range(len(data_arr1)):
        pimval=dic_org_sort[i][1]/(len(data_arr1)-dic_ord_sort[i][1]+1)
        pims.append(pimval)
        spimval+=pimval
    if spimval==0:
        spimval=1
    return [item/spimval*100 for item in pims]

I hope your help


问:
ns typings command error "parse error near `\n'"
I have a really small kotlin library to test how to import it into nativescript.
I've fallen down at the step when creating typings for ns. I'm getting always the same error:
zsh: parse error near \n'`

The steps I did for now...

The kotlin class:

```<code>
package com.example.mytestlibrary

class MyFirst {
    fun getMySentence(): String {
        return "Lorem Ipsum"
    }
}

</code>```

I've built an .aar from the lib in Android Studio and unziped to access the jar file and put the files into NS project.

If I run ns typings android –-jar <./libs/MyTestLibrary/classes.jar>
I get this error: zsh: parse error near `\n'

I can't find out why?

Body:
I have a really small kotlin library to test how to import it into nativescript.
I've fallen down at the step when creating typings for ns. I'm getting always the same error:
zsh: parse error near \n'`

The steps I did for now...

The kotlin class:

package com.example.mytestlibrary

class MyFirst {
    fun getMySentence(): String {
        return "Lorem Ipsum"
    }
}

I've built an .aar from the lib in Android Studio and unziped to access the jar file and put the files into NS project.

If I run ns typings android –-jar <./libs/MyTestLibrary/classes.jar>
I get this error: zsh: parse error near `\n'

I can't find out why?


问:
What does a half filled sample color square in SwiftUI Assets mean?
In Assets Catalog of a Xcode 14.1 project I see color sample squares that are duo colored (half one shade, half another shade).  What does this mean.

Does it have anything to do with the Toggle Appearence Mode (dark / light) that a simulator or device may be set.

I don't know how I got this to happen in Xcode 14.1  - Anyone know how I did this trick?


问:
Error uploading multiple images with Cloudinary
When I try to upload multiple images with Cloudinary and Multer with NestJS I receive an error. I'm able to use the Cloudinary service in other components without issue.

Here is the error I'm getting at restaurant.service.ts:20:38:

Cannot read properties of undefined (Reading map

Here is my code:

async createRestaurant(CreateRestaurantInput: CreateRestaurantDto, user: UserDocument, restaurant?: Restaurant) {
  const { name, address, category, description, email, images, phoneNo } = CreateRestaurantInput

  // 1) Upload images to cloudinary
  const imagesPromise = images.map((image) => this.cloudinary.uploadFile(image))

  const imagesResult = await Promise.all(imagesPromise)

  const imagesLink = []
  const imagesIds = []

  // 3) Push images links & images IDs to the arrays
  imagesResult.forEach((image) => {
    imagesLink.push(image.secure_url)
    imagesIds.push(image.public_id)
  })

  const data = Object.assign({
    restaurant,
    name,
    address,
    category,
    description,
    email,
    phoneNo,
    user: user._id,
    images: imagesLink,
    imagesId: imagesIds
  });

  return await this.restaurantModel.create(data)
}
```


问:
Logstash : Aggregate exception occurred. TypeError: no implicit conversion of String into Integer
I am getting this Type conversion error :no implicit conversion of String into Integer
I have no clue what could be the reason for that.

I have multiple input fields from sql (including string, integer and decimal) to my Filter. Here is my filter aggreagtion :

```<code>filter {
    aggregate {
        task_id => "%{providerid}"
       code => "
            map['providerid'] ||= event.get('providerid')
            map['pricingbytrade'] ||= []
            kpishistorical = {}
            kpiscurrent = {}
            hash = event.to_hash
            hash.each { |key,value|
                if key != 'providerid' && key != 'cbsaid' && key != 'primarytrade' && key != 'cbsapricingscore' && key != 'cbsaname' && key != 'scoreyear' && key != 'type'  && !key.include?('@') && key != 'historicalcbsapricingscore' && !key.start_with?('current')
                    if value.is_a? Numeric
                        value = value.to_f
                    end
                    kpishistorical.store(key, value)
                end
                if key != 'providerid' && key != 'cbsaid' && key != 'primarytrade' && key != 'cbsapricingscore' && key != 'cbsaname' && key != 'scoreyear' && key != 'type'  && !key.include?('@') && !key.start_with?('historical')
                    if value.is_a? Numeric
                        value = value.to_f
                    end
                    kpiscurrent.store(key, value)
                end
            }

           map['pricingbytrade'].find {|m| m['name'] == event.get('primarytrade')}['pricingbycbsa'] <<
                    {
                        'cbsaid' => event.get('cbsaid'),
                        'cbsaname' => event.get('cbsaname'),
                        'pricingscore' => event.get('cbsapricingscore'),
                        'kpis' => kpiscurrent,
                        'historical' => [
                            {
                                'scoremonth' => event.get('scoremonth'),
                                'scoreyear' => event.get('scoreyear'),
                                'pricingscore' => event.get('historicalcbsapricingscore'),
                                'kpis' => kpishistorical
                            }
                        ]
                    }
     event.cancel()
    "
  }
}
</code>```

here cbsapricingscore and historicalcbsapricingscore are decimal input  and cbsaid is integer input to filter.

Can someone help solve this error?

Body:
I am getting this Type conversion error :no implicit conversion of String into Integer
I have no clue what could be the reason for that.

I have multiple input fields from sql (including string, integer and decimal) to my Filter. Here is my filter aggreagtion :

filter {
    aggregate {
        task_id => "%{providerid}"
       code => "
            map['providerid'] ||= event.get('providerid')
            map['pricingbytrade'] ||= []
            kpishistorical = {}
            kpiscurrent = {}
            hash = event.to_hash
            hash.each { |key,value|
                if key != 'providerid' && key != 'cbsaid' && key != 'primarytrade' && key != 'cbsapricingscore' && key != 'cbsaname' && key != 'scoreyear' && key != 'type'  && !key.include?('@') && key != 'historicalcbsapricingscore' && !key.start_with?('current')
                    if value.is_a? Numeric
                        value = value.to_f
                    end
                    kpishistorical.store(key, value)
                end
                if key != 'providerid' && key != 'cbsaid' && key != 'primarytrade' && key != 'cbsapricingscore' && key != 'cbsaname' && key != 'scoreyear' && key != 'type'  && !key.include?('@') && !key.start_with?('historical')
                    if value.is_a? Numeric
                        value = value.to_f
                    end
                    kpiscurrent.store(key, value)
                end
            }

           map['pricingbytrade'].find {|m| m['name'] == event.get('primarytrade')}['pricingbycbsa'] <<
                    {
                        'cbsaid' => event.get('cbsaid'),
                        'cbsaname' => event.get('cbsaname'),
                        'pricingscore' => event.get('cbsapricingscore'),
                        'kpis' => kpiscurrent,
                        'historical' => [
                            {
                                'scoremonth' => event.get('scoremonth'),
                                'scoreyear' => event.get('scoreyear'),
                                'pricingscore' => event.get('historicalcbsapricingscore'),
                                'kpis' => kpishistorical
                            }
                        ]
                    }
     event.cancel()
    "
  }
}

here cbsapricingscore and historicalcbsapricingscore are decimal input  and cbsaid is integer input to filter.

Can someone help solve this error?


问:
How to design the leaf node if I want to fix the node size with variable length kv pair in B tree
How to design the leaf node if I want to fix the node size with variable length kv pair in B+ tree? Say if I want to fix the leaf node size with 4KB and insert as much kv pairs as it can hold. I found that many of implementation of the B+ tree are using array and fix the size of array, but It can not be work for the variable length key or value. I wonder if it could be possible by any chance?</p>


问:
QTSpim only working properly once until i fully close and reopen program
trying to run a test program which involves memory mapped I/O, this is the current testing program to help print out a single character

main:

```<code>li  $s0, 0xffff0000
li  $t0, 0x40 # @
sw  $t0, 12($s0)
nop
li  $v0, 10
syscall
</code>```

the code works fine when i first run it but wont output anything the second time i try to run it until i fully close QTSpim and reopen it, which then only runs once to never being able to run properly in the same session.

Body:
trying to run a test program which involves memory mapped I/O, this is the current testing program to help print out a single character

main:

li  $s0, 0xffff0000
li  $t0, 0x40 # @
sw  $t0, 12($s0)
nop
li  $v0, 10
syscall

the code works fine when i first run it but wont output anything the second time i try to run it until i fully close QTSpim and reopen it, which then only runs once to never being able to run properly in the same session.


问:
Why are params not present when submitting a form with RSpec/Capybara?
This is on a Rails 7 app. We do our feature testing through RSpec and Capybara, using selenium chrome headless.

I have a form used to search for Request records, with a text field to search by name, and an accordion that opens up to reveal more specific filters, in this case: date of birth. Everything works nicely in the browser, but i can't get capybara to submit the form properly.

Here is the partial where I keep the form:

```<code><div class="row">
  <%= form_with url: requests_path,
                method: :get,
                local: true,
                class: 'search-bar' do |f| %>

    <%= inline_svg_tag 'search.svg' %>
    <%= f.text_field :name, class: 'search-field',
                            style: "width: #{field_width};",
                            placeholder: ' search by first, middle, or last name' %>

</div>
<div class="row">
  <div class="accordion col-3 search-position" style="margin-left: <%= left_margin %>;" id="advancedFilters">
    <div class="accordion-item" style="width: 22vw;">
      <h2 class="accordion-header" id="headingOne">
        <button class="accordion-button collapsed search-accordion"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseOne"
                aria-expanded="true"
                aria-controls="collapseOne">
          <span class="grey-text">Advanced filters</span>
        </button>
      </h2>
      <div id="collapseOne"
           class="accordion-collapse collapse"
           aria-labelledby="headingOne"
           data-bs-parent="#advancedFilters">
        <div class="accordion-body container">
          <div class="row">
            <div class="col-6 text-left no-left-pad">
              <%= f.label :date_of_birth, 'Date of birth:', class: 'grey-text fs-6' %>
            </div>
            <div class="col-4 text-left no-left-pad">
              <%= f.date_field :date_of_birth %>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col">
    <%= f.submit 'Search', id: 'searchButton',
                           class: 'btn btn-primary search-btn',
                           onclick: "$('form').submit();",
                           data: {turbo: false} %>
  </div>
</div>
  <% end %>
</code>```

I placed a byebug in the RequestsController#index action, and running the test revealed to me that the params hash was empty. However, if i submit the form myself on localhost, the params hash is populated as expected. Why are the params empty after Capybara submits the form?

Here's the capybara config file:

require 'capybara/rspec'
require 'webdrivers/chromedriver'

Capybara.register_driver(:selenium_chrome_headless) do |app|
  client = Selenium::WebDriver::Remote::Http::Default.new
  client.read_timeout = 120
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_emulation(device_metrics: {width: 1400,
                                         height: 800,
                                         touch: false})
  %w[headless disable-gpu].each do |option|
    options.add_argument(option)
  end

  Capybara::Selenium::Driver.new(app, browser: :chrome,
                                      options: options,
                                      http_client: client)
end

Capybara.default_driver = :rack_test
Capybara.javascript_driver = :selenium_chrome_headless
```
<p>The test:</p>
<pre class="lang-rb prettyprint-override"><code>RSpec.describe 'Searching for Requests', js: true do
  let!(:request1) {
    create(:request, user_id: user.id,
                     first_name: 'Cindy',
                     middle_name: 'Hill',
                     last_name: 'Baldwin',
                     date_of_birth: Date.parse('2000-05-18'))
  }

  let!(:request2) {
    create(:request, user_id: user.id,
                     first_name: 'Andrea',
                     middle_name: 'Marie',
                     last_name: 'Garcia',
                     date_of_birth: Date.parse('2000-05-17'))
  }

  let!(:request3) {
    create(:request, user_id: user.id,
                     first_name: 'Chauncey',
                     middle_name: 'Wynn',
                     last_name: 'Smith',
                     date_of_birth: Date.parse('2000-05-16'))
  }

  let!(:request4) {
    create(:request, user_id: user1.id,
                     first_name: 'Michelle',
                     middle_name: 'Ann',
                     last_name: 'Carey',
                     date_of_birth: Date.parse('2000-05-15'))
  }

  let!(:request5) {
    create(:request, user_id: user1.id,
                     first_name: 'James',
                     middle_name: 'Artur',
                     last_name: 'Tyrell',
                     date_of_birth: Date.parse('2000-05-14'))
  }
  describe 'advanced filters' do
    before do
      visit new_user_session_path
      fill_in :user_email, with: user.email
      fill_in :user_password, with: user.password
      click_button 'Log in'
      page.find_by_id('advancedFilters').click
    end

    it 'can search by date of birth' do
      fill_in :date_of_birth, with: '05-18-2000'
      click_button 'Search'

      expect(page).to have_css "li#request-#{request1.id}"

      not_matched = [request2, request3, request4, request5]
      not_matched.each do |r|
        expect(page).not_to have_css "li#request-#{r.id}"
      end
    end
  end
end
</code>```

I have already tried:

using find with selectors instead of fill_in, based on the answer to this post:

find('input#date_of_birth').set '05-18-2000'
find('button#searchButton').click
```
<ul>
<li>using plain javascript to submit the form:</li>
</ul>
<pre class="lang-rb prettyprint-override"><code>fill_in :date_of_birth, with: '05-18-2000'
find('form').execute_script('this.submit();')
</code>```

adding local: true and/or remote: true to the form_with call

I double checked to make sure all my html is valid; all the
 and <% end %> tags look fine to me

Solution - solved by the first commenter

It turns out having the form_with and end inside of different divs was causing strange behavior. Refactoring the whole form to be inside of the accordion-body div fixed my issue:

```<code><div class="row">
  <div class="accordion col-3 search-position" style="margin-left: <%= left_margin %>;" id="advancedFilters">
    <div class="accordion-item" style="width: 22vw;">
      <h2 class="accordion-header" id="headingOne">
        <button class="accordion-button collapsed search-accordion"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseOne"
                aria-expanded="true"
                aria-controls="collapseOne">
          <span class="grey-text"><%= inline_svg_tag 'search.svg' %>Find a beneficiary</span>
        </button>
      </h2>
      <div id="collapseOne"
           class="accordion-collapse collapse"
           aria-labelledby="headingOne"
           data-bs-parent="#advancedFilters">
        <div class="accordion-body container">
          <%= form_with url: requests_path,
                        method: :get,
                        local: true,
                        class: 'search-bar' do |f| %>

            <div class="row">
              <div class="col text-left">
                <%= f.text_field :name, class: 'search-field full-width', placeholder: ' first, middle, or last name' %>
              </div>
            </div>
            <div class="row">
              <div class="col text-left">
                <%= f.label :date_of_birth, 'Date of birth:', class: 'grey-text fs-6' %>
              </div>
            </div>
            <div class="row">
              <div class="col text-left">
                <%= f.date_field :date_of_birth, class: 'grey-text search-field' %>
              </div>
            </div>
            <div class="row">
              <div class="col text-left">
                <%= f.submit 'Search', class: 'btn btn-primary search-btn half-width',
                                       onclick: "$('form').submit();",
                                       data: {turbo: false} %>
              </div>
            </div>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
This is on a Rails 7 app. We do our feature testing through RSpec and Capybara, using selenium chrome headless.

I have a form used to search for Request records, with a text field to search by name, and an accordion that opens up to reveal more specific filters, in this case: date of birth. Everything works nicely in the browser, but i can't get capybara to submit the form properly.

Here is the partial where I keep the form:

  <%= form_with url: requests_path,
                method: :get,
                local: true,
                class: 'search-bar' do |f| %>

    <%= inline_svg_tag 'search.svg' %>
    <%= f.text_field :name, class: 'search-field',
                            style: "width: #{field_width};",
                            placeholder: ' search by first, middle, or last name' %>

  <div class="accordion col-3 search-position" style="margin-left: <%= left_margin %>;" id="advancedFilters">

        <button class="accordion-button collapsed search-accordion"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseOne"
                aria-expanded="true"
                aria-controls="collapseOne">
          Advanced filters
        </button>

              <%= f.label :date_of_birth, 'Date of birth:', class: 'grey-text fs-6' %>

              <%= f.date_field :date_of_birth %>

    <%= f.submit 'Search', id: 'searchButton',
                           class: 'btn btn-primary search-btn',
                           onclick: "$('form').submit();",
                           data: {turbo: false} %>

  <% end %>

I placed a byebug in the RequestsController#index action, and running the test revealed to me that the params hash was empty. However, if i submit the form myself on localhost, the params hash is populated as expected. Why are the params empty after Capybara submits the form?

Here's the capybara config file:

require 'capybara/rspec'
require 'webdrivers/chromedriver'

Capybara.register_driver(:selenium_chrome_headless) do |app|
  client = Selenium::WebDriver::Remote::Http::Default.new
  client.read_timeout = 120
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_emulation(device_metrics: {width: 1400,
                                         height: 800,
                                         touch: false})
  %w[headless disable-gpu].each do |option|
    options.add_argument(option)
  end

  Capybara::Selenium::Driver.new(app, browser: :chrome,
                                      options: options,
                                      http_client: client)
end

Capybara.default_driver = :rack_test
Capybara.javascript_driver = :selenium_chrome_headless

The test:

RSpec.describe 'Searching for Requests', js: true do
  let!(:request1) {
    create(:request, user_id: user.id,
                     first_name: 'Cindy',
                     middle_name: 'Hill',
                     last_name: 'Baldwin',
                     date_of_birth: Date.parse('2000-05-18'))
  }

  let!(:request2) {
    create(:request, user_id: user.id,
                     first_name: 'Andrea',
                     middle_name: 'Marie',
                     last_name: 'Garcia',
                     date_of_birth: Date.parse('2000-05-17'))
  }

  let!(:request3) {
    create(:request, user_id: user.id,
                     first_name: 'Chauncey',
                     middle_name: 'Wynn',
                     last_name: 'Smith',
                     date_of_birth: Date.parse('2000-05-16'))
  }

  let!(:request4) {
    create(:request, user_id: user1.id,
                     first_name: 'Michelle',
                     middle_name: 'Ann',
                     last_name: 'Carey',
                     date_of_birth: Date.parse('2000-05-15'))
  }

  let!(:request5) {
    create(:request, user_id: user1.id,
                     first_name: 'James',
                     middle_name: 'Artur',
                     last_name: 'Tyrell',
                     date_of_birth: Date.parse('2000-05-14'))
  }
  describe 'advanced filters' do
    before do
      visit new_user_session_path
      fill_in :user_email, with: user.email
      fill_in :user_password, with: user.password
      click_button 'Log in'
      page.find_by_id('advancedFilters').click
    end

    it 'can search by date of birth' do
      fill_in :date_of_birth, with: '05-18-2000'
      click_button 'Search'

      expect(page).to have_css "li#request-#{request1.id}"

      not_matched = [request2, request3, request4, request5]
      not_matched.each do |r|
        expect(page).not_to have_css "li#request-#{r.id}"
      end
    end
  end
end

I have already tried:

using find with selectors instead of fill_in, based on the answer to this post:

find('input#date_of_birth').set '05-18-2000'
find('button#searchButton').click

using plain javascript to submit the form:

fill_in :date_of_birth, with: '05-18-2000'
find('form').execute_script('this.submit();')

adding local: true and/or remote: true to the form_with call

I double checked to make sure all my html is valid; all the
 and <% end %> tags look fine to me

Solution - solved by the first commenter

It turns out having the form_with and end inside of different divs was causing strange behavior. Refactoring the whole form to be inside of the accordion-body div fixed my issue:

  <div class="accordion col-3 search-position" style="margin-left: <%= left_margin %>;" id="advancedFilters">

        <button class="accordion-button collapsed search-accordion"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseOne"
                aria-expanded="true"
                aria-controls="collapseOne">
          <%= inline_svg_tag 'search.svg' %>Find a beneficiary
        </button>

          <%= form_with url: requests_path,
                        method: :get,
                        local: true,
                        class: 'search-bar' do |f| %>

                <%= f.text_field :name, class: 'search-field full-width', placeholder: ' first, middle, or last name' %>

                <%= f.label :date_of_birth, 'Date of birth:', class: 'grey-text fs-6' %>

                <%= f.date_field :date_of_birth, class: 'grey-text search-field' %>

                <%= f.submit 'Search', class: 'btn btn-primary search-btn half-width',
                                       onclick: "$('form').submit();",
                                       data: {turbo: false} %>

          <% end %>


问:
How to check if there is a duplicated field name within my form before register?
I am trying to identify whether within my react final form I have a duplicated name field and then throw an error. I have tried to use a decorator on registerField() and it seems to work fine, however, on a re-render this will not work. I have also tried to use  getRegisterFields() but it seems like its either removing duplicate names or it never registers 2 fields with the same name.
What would you think would be a perfect approach here? Much appreciated.


问:
caffeine cache - Limit size to x MB
Is it possible to set caffeine cache size limited to x MB ?

If this is not possible, is there any performance reason for not doing it [For my understanding].

I checked with weighter,  . As per my understanding weight is calculated based on number of time key was accessed. If i understand weight wrongly please guide me with right link

My use case is to set cache size to x-MB and evict once we reach x-MB

Reference  i used:

https://github.com/ben-manes/caffeine/wiki/Eviction

https://www.tabnine.com/code/java/methods/com.github.benmanes.caffeine.cache.Caffeine/maximumWeight

weight based eviction : https://www.baeldung.com/java-caching-caffeine

Thanks

Jk

Title: caffeine cache - Limit size to x MB


问:
CS50 Trouble with valgrind on problem recover cannot reproduce valgrind message on local machine
I am having trouble getting my code to pass check50, when I run check50 valgrind comes back with this.

```<code>:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:) recovers 000.jpg correctly
:) recovers middle images correctly
:) recovers 049.jpg correctly

:( program is free of memory errors
    valgrind tests failed; see log for more information.

checking that program exited with status 0...
checking for valgrind errors...
Invalid write of size 8: (file: recover.c, line: 84)
Invalid read of size 8: (file: recover.c, line: 84)
Invalid write of size 1: (file: recover.c, line: 88)
Syscall param read(buf) points to unaddressable byte(s): (file: recover.c, line: 88)
Invalid write of size 8: (file: recover.c, line: 88)
Syscall param write(buf) points to unaddressable byte(s): (file: recover.c, line: 102)
Invalid read of size 1: (file: recover.c, line: 102)
</code>```

because of that error I try to run valgrind on my local machine to get the full log, I run valgrind like this

valgrind -s --undef-value-errors=yes --leak-check=full --show-leak-kinds=all -- ./recover card.raw

and this

valgrind ./recover card.raw

but it says no leaks and no problems.

So I also tried running check50 locally and that failed worse than the online check with

```<code>:) recover.c exists.
:) recover.c compiles.

:( handles lack of forensic image
    expected exit code 1, not 127
:( recovers 000.jpg correctly
    expected exit code 0, not 127
:( recovers middle images correctly
    expected exit code 0, not 127
:( recovers 049.jpg correctly
    expected exit code 0, not 127

:| program is free of memory errors
    can't check until a frown turns upside down
</code>```

Here is my program.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

struct byteRange
{
    size_t start;
    size_t end;
};
int findJPGS(FILE *file,  struct byteRange *,  size_t sizeofbyteRange);
int recoverJPGS(FILE *file, struct byteRange *jpgs, size_t numberJpgs);

int main(int argc,  char *argv[])
{
    if (argc != 2)
    {
        printf("proper usage: ./recover IMAGE.raw\n");
        return 1;
    }
    // open image file for reading
    FILE *file = fopen(argv[1],  "r");
    if (file == NULL)
    {
        printf("could not open file for reading\n");
        return 1;
    }
    // read block and check for jpg.
    struct byteRange jpgs[50];
    int numberJpgs = findJPGS(file,  jpgs,  50);
    int result = recoverJPGS(file, jpgs,numberJpgs);

    fclose(file);
    return result;
}

int recoverJPGS(FILE *file, struct byteRange *jpgs, size_t numberJpgs)
{
    // go through byterange list and extract jpgs
    for (size_t i = 0; i < numberJpgs; i++)
    {
        // create a reference to a single byteRange struct.
        struct byteRange range = {.end = 0,.start = 0};
        range = jpgs[i];
        // calculate the image size.
        size_t imageSize = range.end - range.start + 1;
        // create an array of imageSize.
        uint8_t image[imageSize];
        // seek to image start.
        if (fseek(file, (long int)range.start, SEEK_SET) != 0) {
            printf("fseek image number %lu is at fault\n",i);
            return 1;
        }
        // read image into image array.
        if (fread(&image, 1, imageSize, file) != imageSize) {
            printf("fread image number %lu is at fault\n",i);
            printf("returned value %lu != %lu\n",fread(&image, sizeof(uint8_t), imageSize, file),imageSize);
            return 1;
        }

        // write image to file.
        char fileName[50];
        sprintf(fileName,  "%03lu.jpg", i);

        FILE *output = fopen(fileName, "w");
        if (output == NULL)
        {
            printf("could not open file for reading\n");
            return 1;
        }

        fwrite(&image, 1, imageSize, output);
        // close file.
        fclose(output);
    }
    return 0;
}

// returns the number of jpgs found.
int findJPGS(FILE *file,  struct byteRange *jpgs,  size_t size)
{
    uint8_t block[512];
    size_t jpgStart = 0;
    size_t numberJpgs = -1;
    // read every 512 byte block in the file.
    while (fread(&block,  sizeof(uint8_t),  512,  file))
    {
        // check every byte of every block for a byte pattern.
        for (size_t i = 0; i < 512; i++)
        {
            // if a byte contains this run the next level of check.
            if (block[i] == 0xff && i + 3 < 512)
            {
                // check the first and second bytes, and then check the first 4 bits of the third byte.
                if (block[i + 1] == 0xd8 )
                {
                    if (block[i + 2] == 0xff && (block[i + 3] & 0xf0) == 0xe0) {
                        // if this is the first iteration don't bother setting an end byte
                        if (numberJpgs == -1)
                        {
                            numberJpgs = 0;
                            jpgs[numberJpgs].start = jpgStart;
                        }
                        // if this is not the first iteration bother setting the end byte, and set the beggining byte of the next set
                        else
                        {
                            jpgs[numberJpgs].end = jpgStart - 1;
                            numberJpgs++;
                            jpgs[numberJpgs].start = jpgStart;
                        }
                    }
                }
            }
            jpgStart++;
        }
    }
    jpgs[numberJpgs].end = jpgStart - 1;
    numberJpgs++;
    return numberJpgs;
}
</code>```

Here is my Makefile

```<code>recover: recover.c
    clang -g -Qunused-arguments -std=c11 -Wall -Werror -Wextra -Wno-gnu-folding-constant -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow -lm -o recover recover.c
</code>```

So what is the problem with my code?

also bonus question why is my local check50 producing different results from the remote check50, and why are all of them different from raw valgrind?

Body:
I am having trouble getting my code to pass check50, when I run check50 valgrind comes back with this.

:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:) recovers 000.jpg correctly
:) recovers middle images correctly
:) recovers 049.jpg correctly

:( program is free of memory errors
    valgrind tests failed; see log for more information.

checking that program exited with status 0...
checking for valgrind errors...
Invalid write of size 8: (file: recover.c, line: 84)
Invalid read of size 8: (file: recover.c, line: 84)
Invalid write of size 1: (file: recover.c, line: 88)
Syscall param read(buf) points to unaddressable byte(s): (file: recover.c, line: 88)
Invalid write of size 8: (file: recover.c, line: 88)
Syscall param write(buf) points to unaddressable byte(s): (file: recover.c, line: 102)
Invalid read of size 1: (file: recover.c, line: 102)

because of that error I try to run valgrind on my local machine to get the full log, I run valgrind like this

valgrind -s --undef-value-errors=yes --leak-check=full --show-leak-kinds=all -- ./recover card.raw

and this

valgrind ./recover card.raw

but it says no leaks and no problems.

So I also tried running check50 locally and that failed worse than the online check with

:) recover.c exists.
:) recover.c compiles.

:( handles lack of forensic image
    expected exit code 1, not 127
:( recovers 000.jpg correctly
    expected exit code 0, not 127
:( recovers middle images correctly
    expected exit code 0, not 127
:( recovers 049.jpg correctly
    expected exit code 0, not 127

:| program is free of memory errors
    can't check until a frown turns upside down

Here is my program.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

struct byteRange
{
    size_t start;
    size_t end;
};
int findJPGS(FILE *file,  struct byteRange *,  size_t sizeofbyteRange);
int recoverJPGS(FILE *file, struct byteRange *jpgs, size_t numberJpgs);

int main(int argc,  char *argv[])
{
    if (argc != 2)
    {
        printf("proper usage: ./recover IMAGE.raw\n");
        return 1;
    }
    // open image file for reading
    FILE *file = fopen(argv[1],  "r");
    if (file == NULL)
    {
        printf("could not open file for reading\n");
        return 1;
    }
    // read block and check for jpg.
    struct byteRange jpgs[50];
    int numberJpgs = findJPGS(file,  jpgs,  50);
    int result = recoverJPGS(file, jpgs,numberJpgs);

    fclose(file);
    return result;
}

int recoverJPGS(FILE *file, struct byteRange *jpgs, size_t numberJpgs)
{
    // go through byterange list and extract jpgs
    for (size_t i = 0; i < numberJpgs; i++)
    {
        // create a reference to a single byteRange struct.
        struct byteRange range = {.end = 0,.start = 0};
        range = jpgs[i];
        // calculate the image size.
        size_t imageSize = range.end - range.start + 1;
        // create an array of imageSize.
        uint8_t image[imageSize];
        // seek to image start.
        if (fseek(file, (long int)range.start, SEEK_SET) != 0) {
            printf("fseek image number %lu is at fault\n",i);
            return 1;
        }
        // read image into image array.
        if (fread(&image, 1, imageSize, file) != imageSize) {
            printf("fread image number %lu is at fault\n",i);
            printf("returned value %lu != %lu\n",fread(&image, sizeof(uint8_t), imageSize, file),imageSize);
            return 1;
        }

        // write image to file.
        char fileName[50];
        sprintf(fileName,  "%03lu.jpg", i);

        FILE *output = fopen(fileName, "w");
        if (output == NULL)
        {
            printf("could not open file for reading\n");
            return 1;
        }

        fwrite(&image, 1, imageSize, output);
        // close file.
        fclose(output);
    }
    return 0;
}

// returns the number of jpgs found.
int findJPGS(FILE *file,  struct byteRange *jpgs,  size_t size)
{
    uint8_t block[512];
    size_t jpgStart = 0;
    size_t numberJpgs = -1;
    // read every 512 byte block in the file.
    while (fread(&block,  sizeof(uint8_t),  512,  file))
    {
        // check every byte of every block for a byte pattern.
        for (size_t i = 0; i < 512; i++)
        {
            // if a byte contains this run the next level of check.
            if (block[i] == 0xff && i + 3 < 512)
            {
                // check the first and second bytes, and then check the first 4 bits of the third byte.
                if (block[i + 1] == 0xd8 )
                {
                    if (block[i + 2] == 0xff && (block[i + 3] & 0xf0) == 0xe0) {
                        // if this is the first iteration don't bother setting an end byte
                        if (numberJpgs == -1)
                        {
                            numberJpgs = 0;
                            jpgs[numberJpgs].start = jpgStart;
                        }
                        // if this is not the first iteration bother setting the end byte, and set the beggining byte of the next set
                        else
                        {
                            jpgs[numberJpgs].end = jpgStart - 1;
                            numberJpgs++;
                            jpgs[numberJpgs].start = jpgStart;
                        }
                    }
                }
            }
            jpgStart++;
        }
    }
    jpgs[numberJpgs].end = jpgStart - 1;
    numberJpgs++;
    return numberJpgs;
}

Here is my Makefile

recover: recover.c
    clang -g -Qunused-arguments -std=c11 -Wall -Werror -Wextra -Wno-gnu-folding-constant -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow -lm -o recover recover.c

So what is the problem with my code?

also bonus question why is my local check50 producing different results from the remote check50, and why are all of them different from raw valgrind?


问:
Is it possible to have deferred HashSet in Entity Framework Plus?
I am using EF Core in .NET 7 and I can't cache HashSet in EF Plus, so every time I need to iterating all items in that case:

```<code>var emailAlreadyExist = dbContext.Users.Select(c => c.Email).FromCache().Contains(newEmail);
</code>```

Maybe is there some way how can I cache HashSet?
Something like:

```<code>var emailAlreadyExist = dbContext.Users.Select(c => c.Email).DeferredHashSet().FromCache().Contains(newEmail);
</code>```

Body:
I am using EF Core in .NET 7 and I can't cache HashSet in EF Plus, so every time I need to iterating all items in that case:

var emailAlreadyExist = dbContext.Users.Select(c => c.Email).FromCache().Contains(newEmail);

Maybe is there some way how can I cache HashSet?
Something like:

var emailAlreadyExist = dbContext.Users.Select(c => c.Email).DeferredHashSet().FromCache().Contains(newEmail);


问:
Which are the C Standard rules for implicit type coversion?
i fund a post here in SO, that states some rules for implicit type conversion:

— If both operands have the same type, no further conversion is needed.

— Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

— Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

— Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

My first question is, this are all the rules for integer conversion?

And my second question is, can you give me the rules for implicit conversion of floating point types?

Thanks in advance


问:
Is there a way to retrieve all notes from a tumblr post?
This question has been asked a few times before, but none of the answers have ever actually managed to find a way to do this.

Tumblr has an API that you can use in conjunction with pytumblr, but this does not retrieve all notes, it only returns about 50.  I tried using the tumblr api, and didn't manage to get more than 50 notes. I tried using wget to crawl the notes like this user suggested, but it did not work.