问:
what is wrong with this mysql function
```<code>DELIMITER //
    CREATE FUNCTION F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),
    price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2),
    pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) )
        RETURNS float(20,2)
        NOT DETERMINISTIC
        CONTAINS SQL
       SQL SECURITY DEFINER
    BEGIN

     DECLARE FinalPrice VARCHAR(20);
     DECLARE err VARCHAR(20);

     DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1;

    IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN
      IF (pricetopint > 0) THEN
         SET FinalPrice = pricetopint;
       ELSEIF(price > 0)THEN
         SET FinalPrice = price - pricehulcons;
       ELSEIF(estprice > 0)THEN
         SET FinalPrice = estprice - pricehulcons;
        END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN
    IF(pricehulint > 0)THEN
       SET FinalPrice = pricehulint;
     ELSEIF(price > 0)THEN
      SET FinalPrice = price - pricetop;
    ELSEIF(s.estprice > 0)THEN
      SET FinalPrice = estprice - pricetop;
    END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN
    IF(priceint > 0)THEN
      SET FinalPrice = priceint;
    ELSEIF(price > 0)THEN
      SET FinalPrice = price - (pricetop + pricehulcons);
    ELSEIF(estprice > 0)THEN
      SET FinalPrice = estprice - (pricetop + pricehulcons);
    END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN
    IF(priceint > 0)THEN
      SET FinalPrice = priceint;
    ELSEIF(price > 0)THEN
      SET FinalPrice = price - pricetht;
    ELSEIF(estprice > 0)THEN
      SET FinalPrice = estprice - pricetht;
    END IF;

    END IF;

    IF(sbwynum > 0)THEN
    IF(FinalPrice > 0)THEN
      RETURN FinalPrice;
    ELSEIF(adjprice > 0)THEN
       RETURN adjprice;
    ELSEIF(price > 0)THEN
       RETURN price;
    ELSEIF(estprice > 0)THEN
       RETURN estprice;
    ELSE
       RETURN 0;
    END IF;
    ELSE
      RETURN 0;
    END IF;

    END //

    DELIMITER ;
</code>```

ERROR :=

Error
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unclosed quote @ 16
STR: SQL: CREATE FUNCTIONF_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),
price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2),
pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) )
RETURNS float(20,2)
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'THIS FUNCTION WILL USE FOR OFFSHORE PRICING SYSTEM REFERS TO MAIL ID := 40516'
BEGIN

DECLARE FinalPrice VARCHAR(20);
DECLARE err VARCHAR(20);

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1;

IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN
IF (pricetopint > 0) THEN
SET FinalPrice = pricetopint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricehulcons;
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - pricehulcons;
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN
IF(pricehulint > 0)THEN
SET FinalPrice = pricehulint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricetop;
ELSEIF(s.estprice > 0)THEN
SET FinalPrice = estprice - pricetop;
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN
IF(priceint > 0)THEN
SET FinalPrice = priceint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - (pricetop + pricehulcons);
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - (pricetop + pricehulcons);
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN
IF(priceint > 0)THEN
SET FinalPrice = priceint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricetht;
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - pricetht;
END IF;

END IF;

IF(sbwynum > 0)THEN
IF(FinalPrice > 0)THEN
RETURN FinalPrice;
ELSEIF(adjprice > 0)THEN
RETURN adjprice;
ELSEIF(price > 0)THEN
RETURN price;
ELSEIF(estprice > 0)THEN
RETURN estprice;
ELSE
RETURN 0;
END IF;
ELSE
RETURN 0;
END IF;

END //

DELIMITER ;

SQL query:

CREATE FUNCTION `F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2), price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2), pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) ) RETURNS float(20,2) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT 'THIS FUNCTION WILL USE FOR OFFSHORE PRICING SYSTEM REFERS TO MAIL ID := 40516' BEGIN DECLARE FinalPrice VARCHAR(20); DECLARE err VARCHAR(20); DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1; IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN IF (pricetopint > 0) THEN SET FinalPrice = pricetopint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricehulcons; ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - pricehulcons; END IF; END IF; IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN IF(pricehulint > 0)THEN SET FinalPrice = pricehulint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricetop; ELSEIF(s.estprice > 0)THEN SET FinalPrice = estprice - pricetop; END IF; END IF; IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN IF(priceint > 0)THEN SET FinalPrice = priceint; ELSEIF(price > 0)THEN SET FinalPrice = price - (pricetop + pricehulcons); ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - (pricetop + pricehulcons); END IF; END IF; IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN IF(priceint > 0)THEN SET FinalPrice = priceint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricetht; ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - pricetht; END IF; END IF; IF(sbwynum > 0)THEN IF(FinalPrice > 0)THEN RETURN FinalPrice; ELSEIF(adjprice > 0)THEN RETURN adjprice; ELSEIF(price > 0)THEN RETURN price; ELSEIF(estprice > 0)THEN RETURN estprice; ELSE RETURN 0; END IF; ELSE RETURN 0; END IF; END // DELIMITER ;

MySQL said:

1059 - Identifier name 'F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),

pri' is too long

Can anyone please tell me what's wrong with  this user definded function in mysql 5.1 using cpanel bUT IN EMS MANAGER 2007 ITS RUNNING CORRECT.
Thanks a lot...

答:
First line:

```<code>CREATE FUNCTION `F_offshorePrice1(topsbwynum INTEGER...
</code>```

Try:

```<code>CREATE FUNCTION F_offshorePrice1(topsbwynum INTEGER...
</code>```

Or, in case the ` character should be there, it doesn't seem to have a matching closing character...

Title: what is wrong with this mysql function

Body:
DELIMITER //
    CREATE FUNCTION F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),
    price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2),
    pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) )
        RETURNS float(20,2)
        NOT DETERMINISTIC
        CONTAINS SQL
       SQL SECURITY DEFINER
    BEGIN

     DECLARE FinalPrice VARCHAR(20);
     DECLARE err VARCHAR(20);

     DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1;

    IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN
      IF (pricetopint > 0) THEN
         SET FinalPrice = pricetopint;
       ELSEIF(price > 0)THEN
         SET FinalPrice = price - pricehulcons;
       ELSEIF(estprice > 0)THEN
         SET FinalPrice = estprice - pricehulcons;
        END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN
    IF(pricehulint > 0)THEN
       SET FinalPrice = pricehulint;
     ELSEIF(price > 0)THEN
      SET FinalPrice = price - pricetop;
    ELSEIF(s.estprice > 0)THEN
      SET FinalPrice = estprice - pricetop;
    END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN
    IF(priceint > 0)THEN
      SET FinalPrice = priceint;
    ELSEIF(price > 0)THEN
      SET FinalPrice = price - (pricetop + pricehulcons);
    ELSEIF(estprice > 0)THEN
      SET FinalPrice = estprice - (pricetop + pricehulcons);
    END IF;

    END IF;

    IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN
    IF(priceint > 0)THEN
      SET FinalPrice = priceint;
    ELSEIF(price > 0)THEN
      SET FinalPrice = price - pricetht;
    ELSEIF(estprice > 0)THEN
      SET FinalPrice = estprice - pricetht;
    END IF;

    END IF;

    IF(sbwynum > 0)THEN
    IF(FinalPrice > 0)THEN
      RETURN FinalPrice;
    ELSEIF(adjprice > 0)THEN
       RETURN adjprice;
    ELSEIF(price > 0)THEN
       RETURN price;
    ELSEIF(estprice > 0)THEN
       RETURN estprice;
    ELSE
       RETURN 0;
    END IF;
    ELSE
      RETURN 0;
    END IF;

    END //

    DELIMITER ;

ERROR :=

Error
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unclosed quote @ 16
STR: SQL: CREATE FUNCTIONF_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),
price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2),
pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) )
RETURNS float(20,2)
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'THIS FUNCTION WILL USE FOR OFFSHORE PRICING SYSTEM REFERS TO MAIL ID := 40516'
BEGIN

DECLARE FinalPrice VARCHAR(20);
DECLARE err VARCHAR(20);

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1;

IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN
IF (pricetopint > 0) THEN
SET FinalPrice = pricetopint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricehulcons;
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - pricehulcons;
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN
IF(pricehulint > 0)THEN
SET FinalPrice = pricehulint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricetop;
ELSEIF(s.estprice > 0)THEN
SET FinalPrice = estprice - pricetop;
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN
IF(priceint > 0)THEN
SET FinalPrice = priceint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - (pricetop + pricehulcons);
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - (pricetop + pricehulcons);
END IF;

END IF;

IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN
IF(priceint > 0)THEN
SET FinalPrice = priceint;
ELSEIF(price > 0)THEN
SET FinalPrice = price - pricetht;
ELSEIF(estprice > 0)THEN
SET FinalPrice = estprice - pricetht;
END IF;

END IF;

IF(sbwynum > 0)THEN
IF(FinalPrice > 0)THEN
RETURN FinalPrice;
ELSEIF(adjprice > 0)THEN
RETURN adjprice;
ELSEIF(price > 0)THEN
RETURN price;
ELSEIF(estprice > 0)THEN
RETURN estprice;
ELSE
RETURN 0;
END IF;
ELSE
RETURN 0;
END IF;

END //

DELIMITER ;

SQL query:

CREATE FUNCTION `F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2), price FLOAT(11,2), estprice FLOAT(11,2), pricehulint FLOAT(11,2), pricetopint FLOAT(11,2), pricehulcons FLOAT(11,2), pricetop FLOAT(11,2),priceint FLOAT(11,2),pricetht FLOAT(11,2) ) RETURNS float(20,2) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT 'THIS FUNCTION WILL USE FOR OFFSHORE PRICING SYSTEM REFERS TO MAIL ID := 40516' BEGIN DECLARE FinalPrice VARCHAR(20); DECLARE err VARCHAR(20); DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET err = 1; IF(sbwynum > 0 AND hulsbwynum > 0 and sbwynum != hulsbwynum AND (topsbwynum = sbwynum OR topsbwynum < 1 or topsbwynum IS NULL)) THEN IF (pricetopint > 0) THEN SET FinalPrice = pricetopint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricehulcons; ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - pricehulcons; END IF; END IF; IF(sbwynum > 0 AND topsbwynum > 0 and sbwynum != topsbwynum AND (hulsbwynum = sbwynum OR hulsbwynum < 1 or hulsbwynum IS NULL)) THEN IF(pricehulint > 0)THEN SET FinalPrice = pricehulint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricetop; ELSEIF(s.estprice > 0)THEN SET FinalPrice = estprice - pricetop; END IF; END IF; IF(sbwynum > 0 AND topsbwynum != hulsbwynum AND hulsbwynum != sbwynum AND topsbwynum != sbwynum AND topsbwynum > 0 and hulsbwynum > 0 )THEN IF(priceint > 0)THEN SET FinalPrice = priceint; ELSEIF(price > 0)THEN SET FinalPrice = price - (pricetop + pricehulcons); ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - (pricetop + pricehulcons); END IF; END IF; IF(sbwynum > 0 AND topsbwynum = hulsbwynum AND sbwynum != hulsbwynum AND hulsbwynum > 0 )THEN IF(priceint > 0)THEN SET FinalPrice = priceint; ELSEIF(price > 0)THEN SET FinalPrice = price - pricetht; ELSEIF(estprice > 0)THEN SET FinalPrice = estprice - pricetht; END IF; END IF; IF(sbwynum > 0)THEN IF(FinalPrice > 0)THEN RETURN FinalPrice; ELSEIF(adjprice > 0)THEN RETURN adjprice; ELSEIF(price > 0)THEN RETURN price; ELSEIF(estprice > 0)THEN RETURN estprice; ELSE RETURN 0; END IF; ELSE RETURN 0; END IF; END // DELIMITER ;

MySQL said:

1059 - Identifier name 'F_offshorePrice1(topsbwynum INTEGER, hulsbwynum INTEGER,sbwynum INTEGER, adjprice FLOAT(11,2),

pri' is too long

Can anyone please tell me what's wrong with  this user definded function in mysql 5.1 using cpanel bUT IN EMS MANAGER 2007 ITS RUNNING CORRECT.
Thanks a lot...

Body:
First line:

CREATE FUNCTION `F_offshorePrice1(topsbwynum INTEGER...

Try:

CREATE FUNCTION F_offshorePrice1(topsbwynum INTEGER...

Or, in case the ` character should be there, it doesn't seem to have a matching closing character...


来源: stackexchange

问:
why can't compile the code on derived class initialization?
Learning C++ and getting error "no matching function for call to 'Weapon::Weapon(int, const char [4], int, int)'" when creating a weapon istance

```<code>Weapon MyWeapon(1,"test",4,1);
</code>```

Where is the bug?

item.h

```<code>#ifndef ITEM_H
#define ITEM_H
#include <string>
#include <iostream>

using namespace std;
class Item
{
public:
  string name;
  int weight;
  int value;
  Item(string n, int w, int v);

};
#endif
</code>```

item.cpp

```<code>#include <iostream>
#include <string>
#include <vector>
#include "item.h"
using namespace std;
Item::Item(string name, int weight, int value)
{
    name=name;
    weight=weight;
    name=value;
}
</code>```

weapon.h

```<code>#ifndef WEAPON_H
#define WEAPON_H
#include "item.h"
class Weapon : public Item
{
public:
  int damage;
  Weapon();
  Weapon(int damage);
};

#endif
</code>```

weapon.cpp

```<code>#include <iostream>
#include <string>
#include <vector>
#include "weapon.h"
using namespace std;
Weapon::Weapon( damage): Item(name, weight, value){}
</code>```

答:
You're getting "no matching function for call to Weapon::Weapon(int, const char [4], int, int)" because there isn't a constructor with that signature. Change the Weapon definition to something like this:

```<code>class Weapon : public Item
{
public:
  int damage;

  Weapon(int damage, std::string name, int weight, int value);
};
</code>```

Then fix up weapon.cpp to send those arguments to the Item constructor:

```<code>Weapon::Weapon(int damage, std::string name, int weight, int value) :
    Item(name, weight, value),
    damage(damage)
{ }
</code>```

Also a quick side note: using namespace std is considered a bad practice.

ContentLicense: CC BY-SA 4.0

Body:
Learning C++ and getting error "no matching function for call to 'Weapon::Weapon(int, const char [4], int, int)'" when creating a weapon istance

Weapon MyWeapon(1,"test",4,1);

Where is the bug?

item.h

#ifndef ITEM_H
#define ITEM_H
#include <string>
#include <iostream>

using namespace std;
class Item
{
public:
  string name;
  int weight;
  int value;
  Item(string n, int w, int v);

};
#endif

item.cpp

#include <iostream>
#include <string>
#include <vector>
#include "item.h"
using namespace std;
Item::Item(string name, int weight, int value)
{
    name=name;
    weight=weight;
    name=value;
}

weapon.h

#ifndef WEAPON_H
#define WEAPON_H
#include "item.h"
class Weapon : public Item
{
public:
  int damage;
  Weapon();
  Weapon(int damage);
};

#endif

weapon.cpp

#include <iostream>
#include <string>
#include <vector>
#include "weapon.h"
using namespace std;
Weapon::Weapon( damage): Item(name, weight, value){}

Body:
You're getting "no matching function for call to Weapon::Weapon(int, const char [4], int, int)" because there isn't a constructor with that signature. Change the Weapon definition to something like this:

class Weapon : public Item
{
public:
  int damage;

  Weapon(int damage, std::string name, int weight, int value);
};

Then fix up weapon.cpp to send those arguments to the Item constructor:

Weapon::Weapon(int damage, std::string name, int weight, int value) :
    Item(name, weight, value),
    damage(damage)
{ }

Also a quick side note: using namespace std is considered a bad practice.


问:
No qualifying bean of type 'ThreadPoolTaskExecutor' available
I'm using Spring Boot 2.2.4 and I'm trying to a custom Executor

Below are the relevant classes

```<code>@Configuration
@ManagedResource
public class ExecutorConfig {
    @Bean(name = "detailsScraperExecutor")
    public Executor getDetailsAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setQueueCapacity(1000000);
        executor.setThreadNamePrefix("detailsScraperExecutor-");
        executor.initialize();
        return executor;
    }
}
</code>```

and the following class which tries to use it.

```<code>@Component
@Profile("!test")
public class DetailsScraper {
    private static final Logger logger = LoggerFactory.getLogger(DetailsScraper.class);

    @Autowired
    @Qualifier("detailsScraperExecutor")
    private ThreadPoolTaskExecutor detailsScraperExecutor;
}
</code>```

When I run the application I get the following error

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'detailsScraper': Unsatisfied dependency
  expressed through field 'detailsScraperExecutor'; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type
  'org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor'
  available: expected at least 1 bean which qualifies as autowire
  candidate. Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true),
  @org.springframework.beans.factory.annotation.Qualifier(value="detailsScraperExecutor")}

my application.properties

```<code>spring.jmx.enabled=false

spring.datasource.url=jdbc:postgresql://example.com:5432/example
spring.datasource.username=example
spring.datasource.password=password

spring.jpa.open-in-view=false

logging.level.com.gargoylesoftware.htmlunit=ERROR

spring.datasource.hikari.maximumPoolSize = 30

app.properties.parseaddress.endpoint=http://example.com
</code>```

Even though I have named it detailsScraperExecutor Spring can't find it? Why is that?

答:
You need to inject the same type of class as declared in configuration but not a higher-level one. But you can use the lower-level one.</p>

```<code> @Autowired
 private Executor detailsScraperExecutor;
</code>```

Body:
I'm using Spring Boot 2.2.4 and I'm trying to a custom Executor

Below are the relevant classes

@Configuration
@ManagedResource
public class ExecutorConfig {
    @Bean(name = "detailsScraperExecutor")
    public Executor getDetailsAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setQueueCapacity(1000000);
        executor.setThreadNamePrefix("detailsScraperExecutor-");
        executor.initialize();
        return executor;
    }
}

and the following class which tries to use it.

@Component
@Profile("!test")
public class DetailsScraper {
    private static final Logger logger = LoggerFactory.getLogger(DetailsScraper.class);

    @Autowired
    @Qualifier("detailsScraperExecutor")
    private ThreadPoolTaskExecutor detailsScraperExecutor;
}

When I run the application I get the following error

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'detailsScraper': Unsatisfied dependency
  expressed through field 'detailsScraperExecutor'; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type
  'org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor'
  available: expected at least 1 bean which qualifies as autowire
  candidate. Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true),
  @org.springframework.beans.factory.annotation.Qualifier(value="detailsScraperExecutor")}

my application.properties

spring.jmx.enabled=false

spring.datasource.url=jdbc:postgresql://example.com:5432/example
spring.datasource.username=example
spring.datasource.password=password

spring.jpa.open-in-view=false

logging.level.com.gargoylesoftware.htmlunit=ERROR

spring.datasource.hikari.maximumPoolSize = 30

app.properties.parseaddress.endpoint=http://example.com

Even though I have named it detailsScraperExecutor Spring can't find it? Why is that?

Body:
You need to inject the same type of class as declared in configuration but not a higher-level one. But you can use the lower-level one.

 @Autowired
 private Executor detailsScraperExecutor;


问:
set choices in django model
```<code>class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)
</code>```

so i had to make this changes to the two classes but i still doesnt work

```<code>class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)
</code>```

But it still doesn't work what i missing or what is not supposed to be there

答:
Try to use: choices=[(x.value, x.name) for x in LeaveRequestStatus]
for first variant of you enums

Title: set choices in django model

Body:
class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)

so i had to make this changes to the two classes but i still doesnt work

class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)

But it still doesn't work what i missing or what is not supposed to be there


问:
Getting HTML form values
How can I get the value of an HTML form to pass to JavaScript?

Is this correct? My script takes two arguments one from textbox, one from the dropdown box.

```<code><body>
<form name="valform" action="" method="POST">

Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type: <select name="cardtype" id="cardtypeid">
  <option value="visa">Visa</option>
  <option value="mastercard">MasterCard</option>
  <option value="discover">Discover</option>
  <option value="amex">Amex</option>
  <option value="diners">Diners Club</option>
</select><br/>
<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />
</body>
</code>```

答:
My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;
```

Title: Getting HTML form values

Body:
How can I get the value of an HTML form to pass to JavaScript?

Is this correct? My script takes two arguments one from textbox, one from the dropdown box.

<form name="valform" action="" method="POST">

Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox">

Card Type: <select name="cardtype" id="cardtypeid">
  <option value="visa">Visa</option>
  <option value="mastercard">MasterCard</option>
  <option value="discover">Discover</option>
  <option value="amex">Amex</option>
  <option value="diners">Diners Club</option>
</select>

<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />


问:
How to generate an auto answer to a script running from cron
I want to run a shell script from cron, and have it answered automatically. How do I do that?

I tried to put on crontab a script. The system is Linux.
One command of the script prompt a question and must be answered ( Y/N )
Ex :
When the script is executed manually, the script execute the command.
The command prompt the question : Do you intend to delete ? [Y/N]
and the system wait for the response.
I answer "Y" and press ENTER, then the script execute the deletion.

I intend to put this script on crontab.
I wish the command will be answered automatically Yes.
How can I do on crontab ?
Many thanks
/Regards

答:
You can add

--interactive=0

at the end of the command. This will automatically return yes for any cron command asking yes/no.

ContentLicense: CC BY-SA 3.0


问:
How to make an API accessible all the time and not just when the project is executed?
I am making my first mobile app using Xamarin.Forms and FreshMVVM as the architecture and I want this app to get info off my SQL database (which is located in azure) by calling an API Rest. I already know how to develop an Api, and all the SQL and Azure related stuff, as well as how to get info from my API.
But what I don't know is how to access this API when the project in which is created is not executed, in other words, I don't know how to make my API Rest accessible all the time, so the App can access to it whenever is needed.
How do you do this?

Thank you all for your time, hope you have a good day.

答: You need to publish the API to a web host.  Azure App Services.  AWS.  Digital Ocean VM running a web server.  Possibly GoDaddy, though I have never used them.  Your own server.</p>


问:
If I assign a procedure to an object property, can it reference other properties of the object?
Best shown with a simple example, question is the ShowMessage at the bottom:

```<code>type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
    procedure ExternalCaller;
  end;

type
   TProcType = procedure of Object;

type
   TSomeObj = class
   private
      FIdentifier: Integer;
      FCaller    : TProcType;
   public
      property Caller     : TProcType read FCaller write FCaller;
      property Identifier : integer read FIdentifier write FIdentifier;
   end;

[snip]

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
   lSomeObj: TSomeObj;
begin
   lSomeObj := TSomeObj.Create;
   lSomeObj.Identifier := 200;
   lSomeObj.Caller := ExternalCaller;
   lSomeObj.Caller;
   lSomeObj.Free;
end;

procedure TFrmSelfRef.ExternalCaller;
begin
   ShowMessage('Can I access lSomeObj.Identifier (value:200) here?');
end;
</code>```

Reason: I already have a TSomeObj instance containing all the information Caller would require, but the ExternalCaller references other objects/units that I do not want to link (the unit containing) TSomeObj to.

答:
What you are asking for is possible with some ugly TMethod hackery, eg:

type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
    procedure ExternalCaller;
  end;

type
  TProcType = procedure of object;

type
  TSomeObj = class
  private
    FIdentifier: Integer;
    FCaller : TProcType;
  public
    property Caller : TProcType read FCaller write FCaller;
    property Identifier : Integer read FIdentifier write FIdentifier;
  end;

...

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
  lSomeObj: TSomeObj;
  P: TProcType;
begin
  lSomeObj := TSomeObj.Create;
  try
    lSomeObj.Identifier := 200;

    //lSomeObj.Caller := ExternalCaller;
    P := ExternalCaller;
    TMethod(P).Data := lSomeObj;
    lSomeObj.Caller := P;

    lSomeObj.Caller;
  finally
    lSomeObj.Free;
  end;
end;

procedure TFrmSelfRef.ExternalCaller;
begin
  ShowMessage('The Identifier is ' + IntToStr(TSomeObj(Self).Identifier));
end;
```

<p>But this very dangerous if misused. I do not recommend this approach!  I am only presenting it for completeness sake.</p>

<p>Use Peter's solution instead.</p>

<p>Another solution is to move <code>ExternalCaller()</code> to <code>TSomeObj</code>, eg:</p>

<pre class="lang-pascal prettyprint-override"><code>type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
  end;

type
  TProcType = procedure of object;

type
  TSomeObj = class
  private
    FIdentifier: Integer;
    FCaller : TProcType;
  public
    procedure ExternalCaller;
    property Caller : TProcType read FCaller write FCaller;
    property Identifier : Integer read FIdentifier write FIdentifier;
  end;

...

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
  lSomeObj: TSomeObj;
  P: TProcType;
begin
  lSomeObj := TSomeObj.Create;
  try
    lSomeObj.Identifier := 200;
    lSomeObj.Caller := lSomeObj.ExternalCaller;
    lSomeObj.Caller;
  finally
    lSomeObj.Free;
  end;
end;

procedure TSomeObj.ExternalCaller;
begin
  ShowMessage('The Identifier is ' + IntToStr(Identifier));
end;
</code>```

Body:
Best shown with a simple example, question is the ShowMessage at the bottom:

type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
    procedure ExternalCaller;
  end;

type
   TProcType = procedure of Object;

type
   TSomeObj = class
   private
      FIdentifier: Integer;
      FCaller    : TProcType;
   public
      property Caller     : TProcType read FCaller write FCaller;
      property Identifier : integer read FIdentifier write FIdentifier;
   end;

[snip]

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
   lSomeObj: TSomeObj;
begin
   lSomeObj := TSomeObj.Create;
   lSomeObj.Identifier := 200;
   lSomeObj.Caller := ExternalCaller;
   lSomeObj.Caller;
   lSomeObj.Free;
end;

procedure TFrmSelfRef.ExternalCaller;
begin
   ShowMessage('Can I access lSomeObj.Identifier (value:200) here?');
end;

Reason: I already have a TSomeObj instance containing all the information Caller would require, but the ExternalCaller references other objects/units that I do not want to link (the unit containing) TSomeObj to.

Body:
What you are asking for is possible with some ugly TMethod hackery, eg:

type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
    procedure ExternalCaller;
  end;

type
  TProcType = procedure of object;

type
  TSomeObj = class
  private
    FIdentifier: Integer;
    FCaller : TProcType;
  public
    property Caller : TProcType read FCaller write FCaller;
    property Identifier : Integer read FIdentifier write FIdentifier;
  end;

...

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
  lSomeObj: TSomeObj;
  P: TProcType;
begin
  lSomeObj := TSomeObj.Create;
  try
    lSomeObj.Identifier := 200;

    //lSomeObj.Caller := ExternalCaller;
    P := ExternalCaller;
    TMethod(P).Data := lSomeObj;
    lSomeObj.Caller := P;

    lSomeObj.Caller;
  finally
    lSomeObj.Free;
  end;
end;

procedure TFrmSelfRef.ExternalCaller;
begin
  ShowMessage('The Identifier is ' + IntToStr(TSomeObj(Self).Identifier));
end;

But this very dangerous if misused. I do not recommend this approach!  I am only presenting it for completeness sake.

Use Peter's solution instead.

Another solution is to move ExternalCaller() to TSomeObj, eg:

type
  TFrmSelfRef = class(TForm)
    BtnTest: TButton;
    procedure BtnTestClick(Sender: TObject);
  private
  public
  end;

type
  TProcType = procedure of object;

type
  TSomeObj = class
  private
    FIdentifier: Integer;
    FCaller : TProcType;
  public
    procedure ExternalCaller;
    property Caller : TProcType read FCaller write FCaller;
    property Identifier : Integer read FIdentifier write FIdentifier;
  end;

...

procedure TFrmSelfRef.BtnTestClick(Sender: TObject);
var
  lSomeObj: TSomeObj;
  P: TProcType;
begin
  lSomeObj := TSomeObj.Create;
  try
    lSomeObj.Identifier := 200;
    lSomeObj.Caller := lSomeObj.ExternalCaller;
    lSomeObj.Caller;
  finally
    lSomeObj.Free;
  end;
end;

procedure TSomeObj.ExternalCaller;
begin
  ShowMessage('The Identifier is ' + IntToStr(Identifier));
end;


问:
What is best way to create elements and append them to the dom in jquery?
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

```<code>for(var i=0 i<=5; i++){

    var li = $("<li/>");
    li.html("teest "+i);
    $("#ulid").append(li);

}
</code>```

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

答:
You can include the inner HTML in the append text as well as multiple elements at a time, so just build one big string and append it just once.</p>

```<code>var append_text = "";
for (i = 0; i <= 5; i++) {
    append_text += "<li>test " + i + "</li>";
}
$("#ulid").append(append_text);
</code>```

Body:
Let's say I am adding li elements in javascript code with jQuery.

Example 1:

for(var i=0 i<=5; i++){

    var li = $("
");
    li.html("teest "+i);
    $("#ulid").append(li);

}

I've learned that the above example is a bad practice due to the fact that the loop rebuilds dom each time it hits append(li).

If that is the case, what is the best way to do the exact same thing as the above example?

Body:
You can include the inner HTML in the append text as well as multiple elements at a time, so just build one big string and append it just once.

var append_text = "";
for (i = 0; i <= 5; i++) {
    append_text += "<li>test " + i + "</li>";
}
$("#ulid").append(append_text);


问:
The user cant access the edit page
I am creating an admin panel ,admin can edit,delete users, and the user can only see the dashboard and the home page.At the home page i have the user profile and an edit button.The problem is that the user cant see the edit page.I have created another page like the user-edits but the user cant access it.

home.blade.php

```<code><div class="container">
          <h1 class="my-4">Your Profile</h1>
          <div class="row">
            <div class="col-md-8">
              <img class="profile-image-page mr-md-3" src="{{ (isset(Auth::user()->github_id)) ? (Auth::user()->avatar) : (asset('images/avatars/' . Auth::user()->avatar)) }}" alt="{{ Auth::user()->name}}">
            </div>
            <div class="col-md-4">
              <h3 class="my-3">Account</h3>
              <ul>
                <li><b>ID: </b>{{ Auth::user()->id }}</li><hr>
                <li><b>Name: </b>{{ Auth::user()->name }}</li><hr>
                <li><b>Last Name: </b>{{ Auth::user()->lastname }}</li><hr>
                <li><b>Email: </b>{{ Auth::user()->email }}</li><hr>
                <li><b>Phone: </b>{{ Auth::user()->phone }}</li><hr>
                <li><b>Job Title: </b>{{ Auth::user()->jobtitle }}</li><hr>
                <li><b>Department: </b>{{ Auth::user()->department}}</li><hr>
                <a href="/role-edit/{{ Auth::user()->id }}" class="btn btn-success">EDIT</a>
              </ul>
            </div>
          </div>
</code>```

web.php

```<code><?php
use App\User;
use App\Department;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('/page', function () {
    return view('admin.page');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::group(['middleware' => ['auth','admin']], function  () {
    Route::get('/role-register','Admin\DashboardController@registered');/
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');//edit user
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');//delete user
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');//edit department
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');//delete department
    Route::get('/user-edit/{id}', 'HomeController@registeredit');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/dashboard', 'Admin\DashboardController@dbcheck');//DATABASE
</code>```

register-edit.blade.php

```<code>@extends ('layouts.master')

@section('title')
Edit Employee | Admin
@endsection

@section('content')

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="card">
        <div class="card-body">
          <div class="card-header">
            <h3>Edit Profile for Registered Employee.</h3>
          </div>
          <div class="card-body">
            <div class="col-md-6">
              <form action="/role-register-update/{{ $users->id }}" method="POST">
                {{ csrf_field() }}
                {{ method_field('PUT') }}

                <div class="form-group">
                  <label>Name</label>
                  <input type="text" name="name" value="{{ $users->name }}" class="form-control">
                </div>
                <div class="form-group">
                  <label>Last Name</label>
                  <input type="text" name="lastname" value="{{ $users->lastname }}" class="form-control">
                </div>
                <div class="form-group">
                  <label>Phone</label>
                  <input type="text" name="phone" value="{{ $users->phone }}" class="form-control">
                </div>
                <div class="form-group">
                  <label>Email address</label>
                  <input class="form-control" type="email"  value="{{ $users->email }}"name="email" id="email">               </div>
                  <div class="form-group">
                    <label>Job Title</label>
                    <input type="text" name="jobtitle" value="{{ $users->jobtitle }}" class="form-control">
                  </div>
                  <div class="form-group">
                    <label>Department</label>
                    <input type="text" name="department" value="{{ $users->department }}" class="form-control">
                  </div>
                  <button type="submit" class="btn btn-success"> Update </button>
                  <a href="/role-register" class="btn btn-danger"> Cancel </a>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  @endsection

  @section('scripts')

  @endsection
</code>```

答:
The route is using admin middleware, which probably means that only admins would be able to access it

```<code>Route::group(['middleware' => ['auth','admin']], function () {
...
    Route::get('/user-edit/{id}', 'HomeController@registeredit');
});
</code>```

Just move outside:

```<code>Route::group(['middleware' => ['auth','admin']], function () {
...
});
Route::get('/user-edit/{id}', 'HomeController@registeredit');
</code>```

Title: The user cant access the edit page

Body:
I am creating an admin panel ,admin can edit,delete users, and the user can only see the dashboard and the home page.At the home page i have the user profile and an edit button.The problem is that the user cant see the edit page.I have created another page like the user-edits but the user cant access it.

home.blade.php

Your Profile

              github_id)) ? (Auth::user()->avatar) : (asset('images/avatars/' . Auth::user()->avatar)) }}" alt="{{ Auth::user()->name}}">

Account

ID: {{ Auth::user()->id }}

Name: {{ Auth::user()->name }}

Last Name: {{ Auth::user()->lastname }}

Email: {{ Auth::user()->email }}

Phone: {{ Auth::user()->phone }}

Job Title: {{ Auth::user()->jobtitle }}

Department: {{ Auth::user()->department}}

                id }}" class="btn btn-success">EDIT

web.php

<?php
use App\User;
use App\Department;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('/page', function () {
    return view('admin.page');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::group(['middleware' => ['auth','admin']], function  () {
    Route::get('/role-register','Admin\DashboardController@registered');/
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');//edit user
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');//delete user
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');//edit department
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');//delete department
    Route::get('/user-edit/{id}', 'HomeController@registeredit');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/dashboard', 'Admin\DashboardController@dbcheck');//DATABASE

register-edit.blade.php

@extends ('layouts.master')

@section('title')
Edit Employee | Admin
@endsection

@section('content')

Edit Profile for Registered Employee.

              <form action="/role-register-update/{{ $users->id }}" method="POST">
                {{ csrf_field() }}
                {{ method_field('PUT') }}

                  Name
                  <input type="text" name="name" value="{{ $users->name }}" class="form-control">

                  Last Name
                  <input type="text" name="lastname" value="{{ $users->lastname }}" class="form-control">

                  Phone
                  <input type="text" name="phone" value="{{ $users->phone }}" class="form-control">

                  Email address
                  <input class="form-control" type="email"  value="{{ $users->email }}"name="email" id="email">

                    Job Title
                    <input type="text" name="jobtitle" value="{{ $users->jobtitle }}" class="form-control">

                    Department
                    <input type="text" name="department" value="{{ $users->department }}" class="form-control">

                  <button type="submit" class="btn btn-success"> Update </button>
                   Cancel
                </form>

  @endsection

  @section('scripts')

  @endsection

Body:
The route is using admin middleware, which probably means that only admins would be able to access it

Route::group(['middleware' => ['auth','admin']], function () {
...
    Route::get('/user-edit/{id}', 'HomeController@registeredit');
});

Just move outside:

Route::group(['middleware' => ['auth','admin']], function () {
...
});
Route::get('/user-edit/{id}', 'HomeController@registeredit');


答:
You need to explicitly specify all the Item arguments in the Weapon constructor.

Change the header like this:

```<code>Weapon(int damage, string n, int w, int v);
</code>```

And the implementation like that:

```<code>Weapon::Weapon(int damage, string n, int w, int v): damage(damage), Item(name, weight, value){}
</code>```

Title: why can't compile the code on derived class initialization?

Body:
You need to explicitly specify all the Item arguments in the Weapon constructor.

Change the header like this:

Weapon(int damage, string n, int w, int v);

And the implementation like that:

Weapon::Weapon(int damage, string n, int w, int v): damage(damage), Item(name, weight, value){}


问:
How can we generate PWA with Flutter.io
I want to develop a mobile app with flutter.io.

Can I also generate PWA with the framework? similar like we can generate with ionic.

答:
There's currently 2 ways to have a PWA app on Flutter:

Use PWA PubDev library.

Flutter Channel Dev (at Feb 17, 2020 current version is 1.15.3)

If you opt to use Channel Dev, on existence project, use the terminal to hit the command:

flutter create .

if we create a new project, you would have a 2 files: manifest.json and index.html inside your web folder.

While checking index.html you would notice the following script:

```<code>if ('serviceWorker' in navigation) {
  window.addEventListener('load', function () {
     navigator.serviceWorker.register('/flutter_service_worker.js');
  });
}
</code>```

This script creates the PWA support for you and be able to "install" the app on a device (this also includes MacOS)

Follow this GUIDE to complete your PWA functionalities.

Title: How can we generate PWA with Flutter.io

Body:
There's currently 2 ways to have a PWA app on Flutter:

Use PWA PubDev library.

Flutter Channel Dev (at Feb 17, 2020 current version is 1.15.3)

If you opt to use Channel Dev, on existence project, use the terminal to hit the command:

flutter create .

if we create a new project, you would have a 2 files: manifest.json and index.html inside your web folder.

While checking index.html you would notice the following script:

if ('serviceWorker' in navigation) {
  window.addEventListener('load', function () {
     navigator.serviceWorker.register('/flutter_service_worker.js');
  });
}

This script creates the PWA support for you and be able to "install" the app on a device (this also includes MacOS)

Follow this GUIDE to complete your PWA functionalities.


问:
How to perform value check inside class
So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class

```<code>class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)

a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
</code>```

The expected output is

```<code>Vector(1a,a2)
</code>```

I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!

答:
```<code>class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __add__(self, other):
        return Vector(str(self.x) + str(other.x), str(self.y) + str(other.y))
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)

a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
</code>```

Title: How to perform value check inside class

Body:
So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class

class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)

a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)

The expected output is

Vector(1a,a2)

I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!


问:
How to add the style to div that has adjacent sibling using react?
i want to add a class to a div that has adjacent sibling selector.

What i am trying to do?
I have two divs which appear on top of each other. so was thinking to move one div (prev_div) slightly above div(next_div) so they are visible. when next_div is closed the prev_div should get back to its original position.

Below is the html code,

```<code><div class="wrapper">
    <div class="prev_div">previous</div>
    <div class="next_div">next</div>
</div>
</code>```

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

```<code>.wrapper div.prev_div + div.next_div {
    position: relative;
    bottom: 70px;
 }
</code>```

But the above adds the margin to the div with class next_div instead i wanted the position style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

this next_div can be closed with close button. and i am doing the node calculations in render method. the next_div is removed there is no trigger to render...it is taking time to detect it...can i do it in componentdidupdate or so.

could someone help me fix this. thanks.
I think since i am

```<code>render = () => {
    const prev_div = document.querySelector('.wrapper div.prev_div');
    const next_div = document.querySelector('.wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}
</code>```

Also the above doesnt work cause the next_div in the dom is from child component. so even if i put these calculations for node and clases in componentdidupdate...closing the next_div is not recognised soon. there is a delay in it.

thanks.

答:
If I understand you correctly, you don't need to do all this stuff.

If next_div can be closed, just add margin-top: 10px to next_div, so when prev_div is "alone" -- you respect the proper styling

this is simplest css only solution

Body:
i want to add a class to a div that has adjacent sibling selector.

What i am trying to do?
I have two divs which appear on top of each other. so was thinking to move one div (prev_div) slightly above div(next_div) so they are visible. when next_div is closed the prev_div should get back to its original position.

Below is the html code,

previous

next

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

.wrapper div.prev_div + div.next_div {
    position: relative;
    bottom: 70px;
 }

But the above adds the margin to the div with class next_div instead i wanted the position style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

this next_div can be closed with close button. and i am doing the node calculations in render method. the next_div is removed there is no trigger to render...it is taking time to detect it...can i do it in componentdidupdate or so.

could someone help me fix this. thanks.
I think since i am

render = () => {
    const prev_div = document.querySelector('.wrapper div.prev_div');
    const next_div = document.querySelector('.wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}

Also the above doesnt work cause the next_div in the dom is from child component. so even if i put these calculations for node and clases in componentdidupdate...closing the next_div is not recognised soon. there is a delay in it.

thanks.


问:
LinqDataSource set isolation level to READ UNCOMMITTED
Is it possible to somehow set LinqDataSource's IsolationLevel to READ UNCOMMITTED?

I have LinqDataSource bound to pretty nasty SQL Server View (INNER JOIN to multiple tables) and sometimes Deadlock exception is thrown if I load the page with all entries from view while site is under heavy load.

答:
If you want to use LinqDataSource, then try setting the isolation level as part of the DataContext connection itself (would mean that if you use the same DataContext with other code that has different isolation level requirements, you would need to set up different ways of initializing the DataContext).

Other options include:

Open the DataContext in your codebehind, and set the transaction level thee

Access a stored procedure with your LinqDataSource or code, through your DataContext, and inside the stored procedure manually set the isolation level for the transaction.

See this blog post for more on there options.


问:
Making a new DataTable out of two others with same ID using LINQ in C#
I have two data tables that have results from queries made on two different servers. The items from the queries are related by a product ID, I am trying to combine the results into a new data table by joining on the product ids.

The basic structure of the tables are

//Product

product_id | field1 | field2 | field3...

//Inventory

id | fieldA | fieldB | fieldC...

and I want

product_id | field1 | field2 |field3 | fieldA | fieldB |fieldC

when product_id == id

This is pretty trivial to do in SQL but since the two data sets come from different databases on different servers I need to merge the results in my app for users.

The only semi-working solution I have is to get a left and right join from the tables, but I cannot figure out how to merge those results into a new data table. Here is some rough code of how I think it should be done. Any help on this would be appreciated as I am sure there is a much better way to do this.

```<code>var query = from S in Product.AsEnumerable()
            join I in Inventory.AsEnumerable()
            on S.Field<string>("product_id") equals I.Field<string>("id") into COLS
            from entry in COLS
            select entry;

var query2 = from I in Inventory.AsEnumerable()
             join S in Product.AsEnumerable()
             on I.Field<string>("id") equals S.Field<string>("product_id") into COLS2
             from entry in COLS2
             select entry;

var FullJoin = query.Union(query2);

if( FullJoin.Any())
{
    Results = FullJoin.CopyToDataTable<DataRow>();
}

return Results;
</code>```

答:
Try the following code:

```<code>var query = from p1 in P1
                    join p2 in P2
                    on p1.ID equals p2.ProductID
                    select new { p1.ID, p1.Field1, p1.Field2, p1.Field3, p2.FieldA, p2.FieldB, p2.FieldC};
</code>```

Body:
I have two data tables that have results from queries made on two different servers. The items from the queries are related by a product ID, I am trying to combine the results into a new data table by joining on the product ids.

The basic structure of the tables are

//Product

product_id | field1 | field2 | field3...

//Inventory

id | fieldA | fieldB | fieldC...

and I want

product_id | field1 | field2 |field3 | fieldA | fieldB |fieldC

when product_id == id

This is pretty trivial to do in SQL but since the two data sets come from different databases on different servers I need to merge the results in my app for users.

The only semi-working solution I have is to get a left and right join from the tables, but I cannot figure out how to merge those results into a new data table. Here is some rough code of how I think it should be done. Any help on this would be appreciated as I am sure there is a much better way to do this.

var query = from S in Product.AsEnumerable()
            join I in Inventory.AsEnumerable()
            on S.Field<string>("product_id") equals I.Field<string>("id") into COLS
            from entry in COLS
            select entry;

var query2 = from I in Inventory.AsEnumerable()
             join S in Product.AsEnumerable()
             on I.Field<string>("id") equals S.Field<string>("product_id") into COLS2
             from entry in COLS2
             select entry;

var FullJoin = query.Union(query2);

if( FullJoin.Any())
{
    Results = FullJoin.CopyToDataTable<DataRow>();
}

return Results;

Body:
Try the following code:

var query = from p1 in P1
                    join p2 in P2
                    on p1.ID equals p2.ProductID
                    select new { p1.ID, p1.Field1, p1.Field2, p1.Field3, p2.FieldA, p2.FieldB, p2.FieldC};


问:
Python 2.7, Pycryptodome: Can not verify private key signature at server side due to encoding issues
I am sending data in Json format between two nodes using Python Requests module functionality on the client side and Flask server on the server side. I need to digitally sign a Python 2.7 string "some string" with an RSA private key and verify the signature on the server side. I have chosen the Pycryptodome module for this purpose. Unfortunately, json.dumps() [from the Json Python module] requires that the signed hash of the string be converted from the form that Pycryptodome's 'pss' signature function outputs (a byte string) to a unicode string -- json requires unicode:  How to encode bytes in JSON? json.dumps() throwing a TypeError

I am using the base 64 module's base64.b64encode() funtion to transform the digital signature into a form that json.dumps() can process -- the signature is put into a python dictionary with some other stuff before jsonoficatoin -- and decoding on the server side with base64.b64decode in hopes of getting back a byte string that can be processed by the verify() function of Pycryptodome.

```<code># client
hash = SHA256.new(some_string)
sig = pss.new(PrivKey).sign(hash)
finicky_Json = base64.b64encode(sig)
</code>```

...

```<code># server
hash = SHA256.new(some_string)
back_to_normal_sig = base64.b64decode(finicky_Json)
public_key_object = pss.new(PubKey)
public_key_object.verify(hash, back_to_normal_sig)`
</code>```

Unfortunately, I am get in a type error:

raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <type 'unicode'> cannot be passed to C code

What am I missing? Thank You

答: If you the contents you are passing on is ASCII (which it should be) you can wrap the unicode string using str().

Body:
I am sending data in Json format between two nodes using Python Requests module functionality on the client side and Flask server on the server side. I need to digitally sign a Python 2.7 string "some string" with an RSA private key and verify the signature on the server side. I have chosen the Pycryptodome module for this purpose. Unfortunately, json.dumps() [from the Json Python module] requires that the signed hash of the string be converted from the form that Pycryptodome's 'pss' signature function outputs (a byte string) to a unicode string -- json requires unicode:  How to encode bytes in JSON? json.dumps() throwing a TypeError

I am using the base 64 module's base64.b64encode() funtion to transform the digital signature into a form that json.dumps() can process -- the signature is put into a python dictionary with some other stuff before jsonoficatoin -- and decoding on the server side with base64.b64decode in hopes of getting back a byte string that can be processed by the verify() function of Pycryptodome.

# client
hash = SHA256.new(some_string)
sig = pss.new(PrivKey).sign(hash)
finicky_Json = base64.b64encode(sig)

...

# server
hash = SHA256.new(some_string)
back_to_normal_sig = base64.b64decode(finicky_Json)
public_key_object = pss.new(PubKey)
public_key_object.verify(hash, back_to_normal_sig)`

Unfortunately, I am get in a type error:

raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <type 'unicode'> cannot be passed to C code

What am I missing? Thank You


问:
Send Discord Embed of Product Stock Parsed form HTML with BS4 and Requests
So I have the code:

```<code>import requests
import discord
from bs4 import BeautifulSoup

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == 678447420643868674):
                if "test" in message.content:
                    r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
                    soup = BeautifulSoup(r.text, 'html.parser')
                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.description = f"Size {anchor_tag.text} OOS"
                            await message.channel.send(embed=embed)
                        else:
                            embed.description = f"Size {anchor_tag.text}  in stock!"
                            await message.channel.send(embed=embed)
client = MyClient()
client.run('NjY2MDMyMDc0NjM3MTgwOTQ4.XkjBLg.I3dtsL2nkVh_bafTlycSwBApQfU')
</code>```

And that sends the item stock as an embed for each size:
https://gyazo.com/7a7c868d00a99fc3798a3c24feb9ea7e

How would I change the code to make it send for every size in one embed instead of an embed per size?

Thanks :)

答:
Append as such:</p>

```<code>                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.add_field(name= f"Size {anchor_tag.text}", value=":x:", inline= 'true')
                        else:
                            embed.add_field(name= f"Size {anchor_tag.text}", value=f":white_check_mark: | ATC", inline= 'true')
                    await message.channel.send(embed=embed)
</code>```

Body:
So I have the code:

import requests
import discord
from bs4 import BeautifulSoup

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == 678447420643868674):
                if "test" in message.content:
                    r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
                    soup = BeautifulSoup(r.text, 'html.parser')
                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.description = f"Size {anchor_tag.text} OOS"
                            await message.channel.send(embed=embed)
                        else:
                            embed.description = f"Size {anchor_tag.text}  in stock!"
                            await message.channel.send(embed=embed)
client = MyClient()
client.run('NjY2MDMyMDc0NjM3MTgwOTQ4.XkjBLg.I3dtsL2nkVh_bafTlycSwBApQfU')

And that sends the item stock as an embed for each size:
https://gyazo.com/7a7c868d00a99fc3798a3c24feb9ea7e

How would I change the code to make it send for every size in one embed instead of an embed per size?

Thanks :)

Body:
Append as such:

                    for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
                        if "piunavailable" in anchor_tag['class']:
                            embed.add_field(name= f"Size {anchor_tag.text}", value=":x:", inline= 'true')
                        else:
                            embed.add_field(name= f"Size {anchor_tag.text}", value=f":white_check_mark: | ATC", inline= 'true')
                    await message.channel.send(embed=embed)


问:
PyQt5 : Wrapped c/c++ object has been deleted
I am trying to create my own graphicsitem with a circle and its label at the center.

```<code>class circle(QGraphicsItem):
    def __init__(self, radius=None, name=None, x=None, y=None, parent=None):
        super(circle, self).__init__(parent)
        self.radius = radius if radius else random.random()*500
        self.label = name if name else "cirA"
        self.x = x if x else random.randint(0, 900)
        self.y = y if y else random.randint(0, 600)
        # self.center = complex(self.x, self.y)

    def boundingRect(self):
        penWidth = 1.0
        return QRectF(-self.x - penWidth / 2, -self.y - penWidth / 2,
                      self.x + penWidth, self.y + penWidth)

    def paint(self, painter, option, widget):
        painter.drawEllipse(0, 0, self.radius, self.radius)
        painter.drawText(self.label)
</code>```

Now in my main gui, a list of a circles is held as circleList and I am trying to add the circle item as

for cir in self.circleList:
            self.painter.addItem(cir)
```

<p>but this returns</p>

<pre class="lang-sh prettyprint-override"><code>RuntimeError: wrapped C/C++ object of type circle has been deleted
</code>```

help?

this should do the trick for the minimal reproduce able example

note: FBS is required and project should be started using

fbs startproject
```

<p>the circle is also to be added along with the following</p>

<pre class="lang-py prettyprint-override"><code>from fbs_runtime.application_context.PyQt5 import ApplicationContext
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class gui(QDialog):
    def __init__(self, parent=None):
        super(gui, self).__init__(parent)
        self.painter = QGraphicsScene(10, 10, 900, 600)
        self.canvas = QGraphicsView(self.painter)
        mainLayout = QGridLayout()
        mainLayout.addWidget(self.canvas, 0, 0, 6, 2)
        self.setLayout(mainLayout)
        self.circleList = []

    def drawCircle(self):
        pen = QPen(Qt.black, 2, Qt.SolidLine)
        self.painter.clear()
        for cir in self.circleList:
            self.painter.addItem(cir)
        self.painter.update()
        self.canvas.update()
        self.update()

    def newCircle(self, cir):
        self.circleList.append(cir)
        self.drawCircle()

    def addCircle(self):
        return self.newCircle(circle())

if __name__ == "__main__":
    app = ApplicationContext()
    test = gui()
    test.show()
    exit(app.app.exec_())
</code>```

答:
Graphics View Framework does not need you to remove and add the items. In your case, when using clear(), you are removing the items from the scene and you are removing them from the memory, so circleList will have variables that no longer have allocated memory.

On the other hand if you want a custom QGraphicsItem that draws a circle and a text in the center then the boundingRect must have the size of the rectangle ex-inscribed to the circle.

Considering the above, the solution is as follows:

class Circle(QGraphicsItem):
    def __init__(self, radius=None, name="", x=0, y=0, parent=None):
        super(Circle, self).__init__(parent)
        self.radius = radius or random.random() * 500
        self.label = name if name else "cirA"
        self.setPos(x or random.randint(0, 900), y or random.randint(0, 900))

    def boundingRect(self):
        return QRectF(0, 0, self.radius, self.radius)

    def paint(self, painter, option, widget):
        painter.drawEllipse(0, 0, self.radius, self.radius)
        painter.drawText(0, 0, self.radius, self.radius, Qt.AlignCenter, self.label)
```

<pre class="lang-py prettyprint-override"><code>class Gui(QDialog):
    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        self.painter = QGraphicsScene(10, 10, 900, 600)
        self.canvas = QGraphicsView(self.painter)
        mainLayout = QGridLayout(self)
        mainLayout.addWidget(self.canvas)

    @property
    def circleList(self):
        return [item for item in self.painter.items() if isinstance(item, Circle)]

    def newCircle(self, cir):
        self.painter.addItem(cir)
        return cir

    def addCircle(self):
        return self.newCircle(Circle())
</code>```

Body:
I am trying to create my own graphicsitem with a circle and its label at the center.

class circle(QGraphicsItem):
    def __init__(self, radius=None, name=None, x=None, y=None, parent=None):
        super(circle, self).__init__(parent)
        self.radius = radius if radius else random.random()*500
        self.label = name if name else "cirA"
        self.x = x if x else random.randint(0, 900)
        self.y = y if y else random.randint(0, 600)
        # self.center = complex(self.x, self.y)

    def boundingRect(self):
        penWidth = 1.0
        return QRectF(-self.x - penWidth / 2, -self.y - penWidth / 2,
                      self.x + penWidth, self.y + penWidth)

    def paint(self, painter, option, widget):
        painter.drawEllipse(0, 0, self.radius, self.radius)
        painter.drawText(self.label)

Now in my main gui, a list of a circles is held as circleList and I am trying to add the circle item as

for cir in self.circleList:
            self.painter.addItem(cir)

but this returns

RuntimeError: wrapped C/C++ object of type circle has been deleted

help?

this should do the trick for the minimal reproduce able example

note: FBS is required and project should be started using

fbs startproject

the circle is also to be added along with the following

from fbs_runtime.application_context.PyQt5 import ApplicationContext
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class gui(QDialog):
    def __init__(self, parent=None):
        super(gui, self).__init__(parent)
        self.painter = QGraphicsScene(10, 10, 900, 600)
        self.canvas = QGraphicsView(self.painter)
        mainLayout = QGridLayout()
        mainLayout.addWidget(self.canvas, 0, 0, 6, 2)
        self.setLayout(mainLayout)
        self.circleList = []

    def drawCircle(self):
        pen = QPen(Qt.black, 2, Qt.SolidLine)
        self.painter.clear()
        for cir in self.circleList:
            self.painter.addItem(cir)
        self.painter.update()
        self.canvas.update()
        self.update()

    def newCircle(self, cir):
        self.circleList.append(cir)
        self.drawCircle()

    def addCircle(self):
        return self.newCircle(circle())

if __name__ == "__main__":
    app = ApplicationContext()
    test = gui()
    test.show()
    exit(app.app.exec_())

Body:
Graphics View Framework does not need you to remove and add the items. In your case, when using clear(), you are removing the items from the scene and you are removing them from the memory, so circleList will have variables that no longer have allocated memory.

On the other hand if you want a custom QGraphicsItem that draws a circle and a text in the center then the boundingRect must have the size of the rectangle ex-inscribed to the circle.

Considering the above, the solution is as follows:

class Circle(QGraphicsItem):
    def __init__(self, radius=None, name="", x=0, y=0, parent=None):
        super(Circle, self).__init__(parent)
        self.radius = radius or random.random() * 500
        self.label = name if name else "cirA"
        self.setPos(x or random.randint(0, 900), y or random.randint(0, 900))

    def boundingRect(self):
        return QRectF(0, 0, self.radius, self.radius)

    def paint(self, painter, option, widget):
        painter.drawEllipse(0, 0, self.radius, self.radius)
        painter.drawText(0, 0, self.radius, self.radius, Qt.AlignCenter, self.label)

class Gui(QDialog):
    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        self.painter = QGraphicsScene(10, 10, 900, 600)
        self.canvas = QGraphicsView(self.painter)
        mainLayout = QGridLayout(self)
        mainLayout.addWidget(self.canvas)

    @property
    def circleList(self):
        return [item for item in self.painter.items() if isinstance(item, Circle)]

    def newCircle(self, cir):
        self.painter.addItem(cir)
        return cir

    def addCircle(self):
        return self.newCircle(Circle())


问:
Unity - trying to add items at specific locations in Mapbox
I´ve followed a tutorial on YouTube where the developer added items spawning around the player at a certain interval with a max distance on the tile in MapBox. What I am trying to achieve is to add them at specific longitude and latitudes.

The changes I made was to to loop through the max amount of items I want to add, incrementing an i variable. Then instead of spawning the item around the player like newLat = getPlayerPosition() + random; I hardcoded the lat and lon like: case 0: newLat = 48.30791f; newLon = 18.08611f; millenium_item.tag = "MI0"; break;

And each item is added to a list of items.
The behaviour I am expecting is to add each item to the list and then spawn them on the map, but instead only one item gets added, the one that has the exact same latitude and longitude as the player:

```<code>case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
</code>```

Case 3 gets added as it has the same Lat and Lon as my player (where the phone actually is).

```<code>case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
</code>```

Case 4 doesnt get added, but as you can see it is pretty close to the location of Case 3.

I dont know what I am doing wrong. Full code:

```<code>void SpawnItems() {

        itemindex = 100;
        for(int i = 0; i < count; i++)
        {
            if (googleSignIn.locationdata[i] == false)
            {
            MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);
            float newLat = 0;
            float newLon = 0;

            MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
            MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
            millenium_item.tileManager = tileManager;

                switch (i)
                {
                     ...
                case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
                case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
                case 5: newLat = 48.32310f; newLon = 18.09536f; millenium_item.tag = "MI5"; break;
                     ...
                }
                /// OUR LAT: 48.32232 OUR LON: 18.09462

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
        }
        }
</code>```

Then Init looks like this:

```<code>public void Init(float _lat, float _lon) {
    lat = _lat;
    lon = _lon;
    UpdatePosition ();
}
</code>```

and:

```<code>public void UpdatePosition() {
    float x, y;
    Vector3 position = Vector3.zero;

    geodeticOffsetInv (tileManager.getLat * Mathf.Deg2Rad, tileManager.getLon * Mathf.Deg2Rad, lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, out x, out y);

    if ((lat - tileManager.getLat) < 0 && (lon - tileManager.getLon) > 0 || (lat - tileManager.getLat) > 0 && (lon - tileManager.getLon) < 0) {
        position = new Vector3(x, .5f, y);
    }
    else {
        position = new Vector3 (-x, .5f, -y);
    }

    position.x *= 0.300122f;
    position.z *= 0.123043f;

    Debug.Log("Position of inited millenium puzzle: " + position.x + " z: " + position.z);

    transform.position = position;
}
</code>```

答:
Its hard to say exactly what is causing this, but this block of code has a good chance of getting an index out of range exception.

```<code>for(int i = 0; i < count; i++)
{
    if (googleSignIn.locationdata[i] == false)
    {
</code>```

Instead, you should do:

```<code>for(int i = 0; i < googleSignIn.locationdata.length; i++)
{
    if (googleSignIn.locationdata[i] == false)
    {
</code>```

But, there is another problem.

Both this class and the googleSignIn class initialize themselves in Start(), and you are not guaranteed that googleSignIn will execute first.  To fix this, you should move the SpawnItems(); call to Awake() instead of Start()

Body:
I´ve followed a tutorial on YouTube where the developer added items spawning around the player at a certain interval with a max distance on the tile in MapBox. What I am trying to achieve is to add them at specific longitude and latitudes.

The changes I made was to to loop through the max amount of items I want to add, incrementing an i variable. Then instead of spawning the item around the player like newLat = getPlayerPosition() + random; I hardcoded the lat and lon like: case 0: newLat = 48.30791f; newLon = 18.08611f; millenium_item.tag = "MI0"; break;

And each item is added to a list of items.
The behaviour I am expecting is to add each item to the list and then spawn them on the map, but instead only one item gets added, the one that has the exact same latitude and longitude as the player:

case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;

Case 3 gets added as it has the same Lat and Lon as my player (where the phone actually is).

case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;

Case 4 doesnt get added, but as you can see it is pretty close to the location of Case 3.

I dont know what I am doing wrong. Full code:

void SpawnItems() {

        itemindex = 100;
        for(int i = 0; i < count; i++)
        {
            if (googleSignIn.locationdata[i] == false)
            {
            MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);
            float newLat = 0;
            float newLon = 0;

            MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
            MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
            millenium_item.tileManager = tileManager;

                switch (i)
                {
                     ...
                case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
                case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
                case 5: newLat = 48.32310f; newLon = 18.09536f; millenium_item.tag = "MI5"; break;
                     ...
                }
                /// OUR LAT: 48.32232 OUR LON: 18.09462

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
        }
        }

Then Init looks like this:

public void Init(float _lat, float _lon) {
    lat = _lat;
    lon = _lon;
    UpdatePosition ();
}

and:

public void UpdatePosition() {
    float x, y;
    Vector3 position = Vector3.zero;

    geodeticOffsetInv (tileManager.getLat * Mathf.Deg2Rad, tileManager.getLon * Mathf.Deg2Rad, lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, out x, out y);

    if ((lat - tileManager.getLat) < 0 && (lon - tileManager.getLon) > 0 || (lat - tileManager.getLat) > 0 && (lon - tileManager.getLon) < 0) {
        position = new Vector3(x, .5f, y);
    }
    else {
        position = new Vector3 (-x, .5f, -y);
    }

    position.x *= 0.300122f;
    position.z *= 0.123043f;

    Debug.Log("Position of inited millenium puzzle: " + position.x + " z: " + position.z);

    transform.position = position;
}

Body:
Its hard to say exactly what is causing this, but this block of code has a good chance of getting an index out of range exception.

for(int i = 0; i < count; i++)
{
    if (googleSignIn.locationdata[i] == false)
    {

Instead, you should do:

for(int i = 0; i < googleSignIn.locationdata.length; i++)
{
    if (googleSignIn.locationdata[i] == false)
    {

But, there is another problem.

Both this class and the googleSignIn class initialize themselves in Start(), and you are not guaranteed that googleSignIn will execute first.  To fix this, you should move the SpawnItems(); call to Awake() instead of Start()


问:
Switch case conflict with dropdownlist availability/panel visibility?
I'm using C# ASP.NET, and I've got a submission page which, when you click the add product link, opens a popup "add product" page that has a dropdown list of products which can be added to a submission. Business rules dictate there can be only one instance of each product on any submission, so I've run two separate switch case statements, one to eliminate items from the drop down list once they've been selected in the popup, and one which queries the db to determine if there are any products already associated with the submission, and if so, eliminate those options from the drop down as well. Once the user selects an item from the dropdown, a panel for that product is made visible for user input.

Both of these switch cases function, in that they eliminate the items which should not be available, but since I put in the queried switch case, the panels no longer become visible upon selection. When I remove the queried switch case, the panels do become visible upon selection, but the products which are already associated with the submission are still available in the dropdown.

I know there is a conflict here somewhere, but I'm racked as to what it is as this is my first go at programming. The code is below. Please disregard the queries themselves; this is a non-active training project and my handler forbade parameterization because he wanted me to learn basics first. I understand the injection vulnerabilities.

```<code>    public partial class AddProduct : System.Web.UI.Page
{

protected void BtnAddProduct_Click(object sender, EventArgs e)
{
    switch (DdlProductList.SelectedValue)
    {
        case "1":
            PanelEpl.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "2":
            PanelProf.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "3":
            PanelCrime.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "4":
            PanelFid.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "5":
            PanelNotProf.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "6":
            PanelPriv.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "7":
            PanelPub.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        default:

                break;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        string x = Request.QueryString["SubId"];
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        string displayQuery = "SELECT CustName, CustAdd, CustCity, CustState, CustZip FROM Customer WHERE SubId =" + x;
        string broQuery = "SELECT EntityType FROM Broker WHERE SubId =" + x;
        string ddlQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
        using (SqlConnection displayConn = new SqlConnection(connectionString))
        {
            displayConn.Open();
            SqlCommand DlistCmd = new SqlCommand(ddlQuery, displayConn);

            using (SqlDataReader Ddldr = DlistCmd.ExecuteReader())
            {
                while (Ddldr.Read())
                {

                    switch (Ddldr.GetInt32(0))
                    {
                        case 1:
                            DdlProductList.Items.RemoveAt(1);
                            break;
                        case 2:
                            DdlProductList.Items.RemoveAt(2);
                            break;
                        case 3:
                            DdlProductList.Items.RemoveAt(3);
                            break;
                        case 4:
                            DdlProductList.Items.RemoveAt(4);
                            break;
                        case 5:
                            DdlProductList.Items.RemoveAt(5);
                            break;
                        case 6:
                            DdlProductList.Items.RemoveAt(6);
                            break;
                        case 7:
                            DdlProductList.Items.RemoveAt(7);
                            break;
                        default:
                            break;
                    }

                }

            }
</code>```

答:
I think you are not considering the Page postback state. Put your page_load code under the If(!IsPostBack) condition:

```<code>protected void Page_Load(object sender, EventArgs e)
{
 If(!IsPostBack)
 {
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string displayQuery = "SELECT CustName, CustAdd, CustCity, CustState, CustZip FROM Customer WHERE SubId =" + x;
    string broQuery = "SELECT EntityType FROM Broker WHERE SubId =" + x;
    string ddlQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
    using (SqlConnection displayConn = new SqlConnection(connectionString))
    {
        displayConn.Open();
        SqlCommand DlistCmd = new SqlCommand(ddlQuery, displayConn);

        using (SqlDataReader Ddldr = DlistCmd.ExecuteReader())
        {
            while (Ddldr.Read())
            {

                switch (Ddldr.GetInt32(0))
                {
                    case 1:
                        DdlProductList.Items.RemoveAt(1);
                        break;
                    case 2:
                        DdlProductList.Items.RemoveAt(2);
                        break;
                    case 3:
                        DdlProductList.Items.RemoveAt(3);
                        break;
                    case 4:
                        DdlProductList.Items.RemoveAt(4);
                        break;
                    case 5:
                        DdlProductList.Items.RemoveAt(5);
                        break;
                    case 6:
                        DdlProductList.Items.RemoveAt(6);
                        break;
                    case 7:
                        DdlProductList.Items.RemoveAt(7);
                        break;
                    default:
                        break;
                }

            }

        }
</code>```

Body:
I'm using C# ASP.NET, and I've got a submission page which, when you click the add product link, opens a popup "add product" page that has a dropdown list of products which can be added to a submission. Business rules dictate there can be only one instance of each product on any submission, so I've run two separate switch case statements, one to eliminate items from the drop down list once they've been selected in the popup, and one which queries the db to determine if there are any products already associated with the submission, and if so, eliminate those options from the drop down as well. Once the user selects an item from the dropdown, a panel for that product is made visible for user input.

Both of these switch cases function, in that they eliminate the items which should not be available, but since I put in the queried switch case, the panels no longer become visible upon selection. When I remove the queried switch case, the panels do become visible upon selection, but the products which are already associated with the submission are still available in the dropdown.

I know there is a conflict here somewhere, but I'm racked as to what it is as this is my first go at programming. The code is below. Please disregard the queries themselves; this is a non-active training project and my handler forbade parameterization because he wanted me to learn basics first. I understand the injection vulnerabilities.

    public partial class AddProduct : System.Web.UI.Page
{

protected void BtnAddProduct_Click(object sender, EventArgs e)
{
    switch (DdlProductList.SelectedValue)
    {
        case "1":
            PanelEpl.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "2":
            PanelProf.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "3":
            PanelCrime.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "4":
            PanelFid.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "5":
            PanelNotProf.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "6":
            PanelPriv.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        case "7":
            PanelPub.Visible = true;
            DdlProductList.Items.Remove(DdlProductList.SelectedItem);
            break;
        default:

                break;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        string x = Request.QueryString["SubId"];
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        string displayQuery = "SELECT CustName, CustAdd, CustCity, CustState, CustZip FROM Customer WHERE SubId =" + x;
        string broQuery = "SELECT EntityType FROM Broker WHERE SubId =" + x;
        string ddlQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
        using (SqlConnection displayConn = new SqlConnection(connectionString))
        {
            displayConn.Open();
            SqlCommand DlistCmd = new SqlCommand(ddlQuery, displayConn);

            using (SqlDataReader Ddldr = DlistCmd.ExecuteReader())
            {
                while (Ddldr.Read())
                {

                    switch (Ddldr.GetInt32(0))
                    {
                        case 1:
                            DdlProductList.Items.RemoveAt(1);
                            break;
                        case 2:
                            DdlProductList.Items.RemoveAt(2);
                            break;
                        case 3:
                            DdlProductList.Items.RemoveAt(3);
                            break;
                        case 4:
                            DdlProductList.Items.RemoveAt(4);
                            break;
                        case 5:
                            DdlProductList.Items.RemoveAt(5);
                            break;
                        case 6:
                            DdlProductList.Items.RemoveAt(6);
                            break;
                        case 7:
                            DdlProductList.Items.RemoveAt(7);
                            break;
                        default:
                            break;
                    }

                }

            }

Body:
I think you are not considering the Page postback state. Put your page_load code under the If(!IsPostBack) condition:

protected void Page_Load(object sender, EventArgs e)
{
 If(!IsPostBack)
 {
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string displayQuery = "SELECT CustName, CustAdd, CustCity, CustState, CustZip FROM Customer WHERE SubId =" + x;
    string broQuery = "SELECT EntityType FROM Broker WHERE SubId =" + x;
    string ddlQuery = "SELECT ProductId FROM SubmissionProducts WHERE SubmissionId =" + x;
    using (SqlConnection displayConn = new SqlConnection(connectionString))
    {
        displayConn.Open();
        SqlCommand DlistCmd = new SqlCommand(ddlQuery, displayConn);

        using (SqlDataReader Ddldr = DlistCmd.ExecuteReader())
        {
            while (Ddldr.Read())
            {

                switch (Ddldr.GetInt32(0))
                {
                    case 1:
                        DdlProductList.Items.RemoveAt(1);
                        break;
                    case 2:
                        DdlProductList.Items.RemoveAt(2);
                        break;
                    case 3:
                        DdlProductList.Items.RemoveAt(3);
                        break;
                    case 4:
                        DdlProductList.Items.RemoveAt(4);
                        break;
                    case 5:
                        DdlProductList.Items.RemoveAt(5);
                        break;
                    case 6:
                        DdlProductList.Items.RemoveAt(6);
                        break;
                    case 7:
                        DdlProductList.Items.RemoveAt(7);
                        break;
                    default:
                        break;
                }

            }

        }


问:
How can I globally set the PATH environment variable in VS Code?
I'm defining a custom $PATH environment variable in my ~/.bash_profile (on a Mac), like so:

```<code>PATH="$HOME/.cargo/bin:$PATH:$HOME/bin"
</code>```

However, VS Code of course does not run my .bash_profile, so it does not have my custom paths. In fact, if I Toggle Developer Tools and check process.env.PATH, it doesn't even seem to have /usr/local/bin.

How do I globally set the PATH environment variable in VS Code?

(I want to set it globally, not per project or per task, since I'm maintaining a lot of small packages.)

答: What did the trick in my case (Linux Mint 19.3 Cinnamon, VS code installed via snap) was to put my appended PATH in ~/.profile . Since this file is read at the beginning of a user session, don't forget to logout/login or reboot after editing this file.</p>

Body:
I'm defining a custom $PATH environment variable in my ~/.bash_profile (on a Mac), like so:

PATH="$HOME/.cargo/bin:$PATH:$HOME/bin"

However, VS Code of course does not run my .bash_profile, so it does not have my custom paths. In fact, if I Toggle Developer Tools and check process.env.PATH, it doesn't even seem to have /usr/local/bin.

How do I globally set the PATH environment variable in VS Code?

(I want to set it globally, not per project or per task, since I'm maintaining a lot of small packages.)