问:
Testing (if..Else if...Else) statement (not working)
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work</p>

```<code>//package Driver2;

import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
   r =  this.customerPurchase;
    if (r > 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}
public int getcustomerDiscount()
{
    return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors
/*
public int getcustomerDiscount()
{
    return this.customerDiscount;
}
/*
@Override
public int getcustomerPurchase()
{
    return this.customerPurchase;
}

//Mutators

@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

/*
public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}
</code>```

答:
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:

```<code>if  r >= 2000  print 10%
else if  r >= 1500  print 7%
else if  r >= 1000  print 6%
else if  r >= 500   print 5%
else print nothing
</code>```

I hope that helps you

Body:
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work

//package Driver2;

import java.util.Scanner;

class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;

//Constructors
public Person(String name, String address, String number, int customerPurchase){
    this.name = name;
    this.address = address;
    this.number = number;
    this.customerPurchase = customerPurchase;
}

public Person(){}

//Accessors
public String getName(){
    return this.name;
}

public String getAddress(){
    return this.address;
}

public String getNumber(){
    return this.number;
}

public int getcustomerPurchase(){
    return this.customerPurchase;
}

//Mutators
public void setName(String n){
    this.name = n;
}

public void setAddress(String a){
    this.address = a;
}

public void setNumber(String n){
    this.number = n;
}

public void setcustomerPurchase(int a){
    this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
   r =  this.customerPurchase;
    if (r > 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}

}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;

//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    super(name, address, number, customerPurchase);
    this.customerNumber = customerN;
    this.recieveMail = rm;
}

public Customer(){}

//Accessors
public String getCustomerNumber(){
    return this.customerNumber;
}

public boolean getRecieveMail(){
    return this.recieveMail;
}
public int getcustomerDiscount()
{
    return customerDiscount;
}

//Mutators
public void setCustomerNumber(String c){
    this.customerNumber = c;
}

public void setRecieveMail(boolean r){
    this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;

//Constructors
   /* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
    super();
    this.customerPurchase = customerPurchase;
    //this.customerDiscount = customerDiscount;
}*/
    public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
    //super(name, address, number, customerPurchase, customerN, rm);
    //this.customerPurchase = customerN;
    //this.customerDiscount = pc;
}

public Driver1()
{}

//Accessors
/*
public int getcustomerDiscount()
{
    return this.customerDiscount;
}
/*
@Override
public int getcustomerPurchase()
{
    return this.customerPurchase;
}

//Mutators

@Override
public void setcustomerPurchase(int c)
{
    this.customerPurchase = c;
}*/

/*
public void setcustomerDiscount(int r)
{
    this.customerPurchase = r;
    if (r >= 500)
    {
        System.out.print("5%");
    }
    else if (r >= 1000)
    {
        System.out.print("6%");
    }
    else if (r >= 1500)
    {
        System.out.print("7%");
    }
    else if (r >= 2000)
    {
        System.out.print("10%");
    }
    else
    {
        System.out.print("");
    }
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter name of customer:");
    String name1 = scanner.nextLine();
    System.out.print("Enter address of customer:");
    String address1 = scanner.nextLine();
    System.out.print("Enter phone number of customer:");
    String number1 = scanner.nextLine();
    System.out.print("Enter customer number:");
    String customerNumber = scanner.nextLine();
    System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
    String answer = scanner.nextLine();
    boolean recieveMail = (answer.equals("yes"));
    System.out.print("Enter amount customer has spent:");
    int customerPurchase = scanner.nextInt();

    Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);

    System.out.println("\nCustomer: ");
    System.out.println("Name: "+customer.getName());
    System.out.println("Address: "+customer.getAddress());
    System.out.println("Phone Number: "+customer.getNumber());
    System.out.println("Customer Number: "+customer.getCustomerNumber());
    System.out.println("Recieve Mail?: "+customer.getRecieveMail());
    System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
    System.out.println("Percent off:  "+customer.getcustomerDiscount());

}
}

Body:
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:

if  r >= 2000  print 10%
else if  r >= 1500  print 7%
else if  r >= 1000  print 6%
else if  r >= 500   print 5%
else print nothing

I hope that helps you


来源: stackexchange

问:
How to concatenate two arrays using PHP?
I have two arrays:

```<code>$browser = array("firefox", "opera", "edge");
$version = array("10", "12", "14");
</code>```

I want to concatenate them such a way that the final array should be:

```<code>array(0=>array("name"=>"firefox", "version"=>"10"), 1=>array("name"=>"opera", "version"=>"12"), 2=>array("name"=>"edge", "version"=>"14"));
</code>```

The code can contain any builtin or user defined function. I have tried using:

```<code>$browser = array("firefox","opera","edge");
$version = array("10","12","14");
foreach($browser as $key=>$values){
  if(!isset($array)){
    $array = array("name"=>$browser[$key],"version"=>$version[$key]);
  }else{
    $array = array($array,array("name"=>$browser[$key],"version"=>$version[$key]));
  }
}
print_r($array);
</code>```

And the output I got was:

```<code>Array ( [0] => Array ( [0] => Array ( [name] => firefox [version] => 10 ) [1] => Array ( [name] => opera [version] => 12 ) ) [1] => Array ( [name] => edge [version] => 14 ) )
</code>```

Also note that this code is in PHP and should work for at least 10 arrays length data.

答:
```<code>$result = array();
for ($i=0; $i<count($browser); $i++) {
  $result[] = array($browser[$i], $version[$i]);
}
return $result;
</code>```

Very simple - just loop through the one array and use indexes.

ContentLicense: CC BY-SA 4.0

Body:
I have two arrays:

$browser = array("firefox", "opera", "edge");
$version = array("10", "12", "14");

I want to concatenate them such a way that the final array should be:

array(0=>array("name"=>"firefox", "version"=>"10"), 1=>array("name"=>"opera", "version"=>"12"), 2=>array("name"=>"edge", "version"=>"14"));

The code can contain any builtin or user defined function. I have tried using:

$browser = array("firefox","opera","edge");
$version = array("10","12","14");
foreach($browser as $key=>$values){
  if(!isset($array)){
    $array = array("name"=>$browser[$key],"version"=>$version[$key]);
  }else{
    $array = array($array,array("name"=>$browser[$key],"version"=>$version[$key]));
  }
}
print_r($array);

And the output I got was:

Array ( [0] => Array ( [0] => Array ( [name] => firefox [version] => 10 ) [1] => Array ( [name] => opera [version] => 12 ) ) [1] => Array ( [name] => edge [version] => 14 ) )

Also note that this code is in PHP and should work for at least 10 arrays length data.

Body:
$result = array();
for ($i=0; $i<count($browser); $i++) {
  $result[] = array($browser[$i], $version[$i]);
}
return $result;

Very simple - just loop through the one array and use indexes.


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
What ever makes your code more readable, maintainable and easier for YOU.
I would have used the simple array, simpler==better most of the time.
Although I really have to see the context to give the right answer.</p>

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Itay Moav


问:
For the current iphone version,  MMS is possible or not?

Possible Duplicate:

  Is it possible to send a picture message using iPhone SDK?

Hi all ,
does MMS way of sending images/text is possible in iPhone ?/
i have used SMS and mail for sending images im just want to make things for MMS .
is there any way to send MMS programmatically??

Thanks

答: The MFMessageComposeViewController does not support MMS, there is no other way then to create you own MMS gateway to allow your app to support MMS.</p>

ContentLicense: CC BY-SA 3.0


问:
Kubernetes load balancer External IP pending
I create RabbitMQ cluster inside Kubernetes. I am trying to add loadbalancer. But I cant get the loadbalancer External-IP it is still pending.

```<code>apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
  labels:
    run: rabbitmq
spec:
  type: NodePort
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  selector:
    run: rabbitmq
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      run: rabbitmq
  template:
    metadata:
      labels:
        run: rabbitmq
    spec:
      containers:
      - name: rabbitmq
        image: rabbitmq:latest
        imagePullPolicy: Always
</code>```

And My load balancer is below. I gave loadbalancer
nodePort is random,
port number is from kubernetes created RabbitMQ mqtt port number,
target port number is from kubernetes created RabbitMQ UI port number

```<code>apiVersion: v1
kind: Service
metadata:
  name: loadbalanceservice
  labels:
    app: rabbitmq
spec:
  selector:
    app: rabbitmq
  type: LoadBalancer
  ports:
  - nodePort: 31022
    port: 30601
    targetPort: 31533
</code>```

答: service type Loadbalancer only works on cloud providers which support external load balancers.Setting the type field to LoadBalancer provisions a load balancer for your Service.It's pending because the environment that you are in is not supporting Loadbalancer type of service.In a non cloud environment an easier option would be to use nodeport type service. Here is a guide on using Nodeport to access service from outside the cluster.</p>

Body:
I create RabbitMQ cluster inside Kubernetes. I am trying to add loadbalancer. But I cant get the loadbalancer External-IP it is still pending.

apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
  labels:
    run: rabbitmq
spec:
  type: NodePort
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  selector:
    run: rabbitmq
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      run: rabbitmq
  template:
    metadata:
      labels:
        run: rabbitmq
    spec:
      containers:
      - name: rabbitmq
        image: rabbitmq:latest
        imagePullPolicy: Always

And My load balancer is below. I gave loadbalancer
nodePort is random,
port number is from kubernetes created RabbitMQ mqtt port number,
target port number is from kubernetes created RabbitMQ UI port number

apiVersion: v1
kind: Service
metadata:
  name: loadbalanceservice
  labels:
    app: rabbitmq
spec:
  selector:
    app: rabbitmq
  type: LoadBalancer
  ports:
  - nodePort: 31022
    port: 30601
    targetPort: 31533


问:
WHERE DATE_COLUMN = '9999-12-31' statements causes query to return no results
I have a very odd problem with a query I was given to convert from Access to SQL Server.

The query works as expected until I add a condition in the WHERE clause to check for a specific date.

I was not sure that the date fields were compatible due to the SQL Server query needing to talk to a linked DB2 mainframe. So to test this to make sure the date is being read correctly I used DATEDIFF(). I also reduced the select statement to only the date field that is having the issue to try and figure out what is going on but I still have had no luck. I have tried ever way I can think of to filter the date.

I tried a HAVING clause.

```<code>HAVING TERM_DT = '9999-12-31'
</code>```

I tried a WHERE clause.

```<code>WHERE TERM_DT = '9999-12-31'
</code>```

I tried to compare the date in the JOIN.

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```

I tried to CAST and CONVERT the field to DATE thinking maybe the date fields were incompatible.

```<code>CAST(TERM_DT AS DATE) = CAST('9999-12-31' AS DATE)
CONVERT(DATE, TERM_DT) = CONVERT(DATE, '9999-12-31')
</code>```

In each of the above I also tried TERM_DT >= '9990-12-31' because nothing else worked and for some reason that column has a few typos like 9998-12-31 and 9999-11-31 so I figured checking from 9990 on should catch everything. Still nothing returned.

The last thing I tried was DATEDIFF(). And that didn't work either.

```<code>DATEDIFF(day, '9990-12-31', TERM_DT) >= 0
</code>```

Except when I placed the DATEDIFF() in the select statement and do not use anything in the WHERE section I get the values I expect...

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
</code>```

Data returned:

```<code>DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
3287        9999-12-31
3287        9999-12-31
</code>```

But when I add the where statement in:

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) >= 0
</code>```

I get no results:

```<code>DIFF        DT
</code>```

Then I tried to flip the comparison with <= and the odd thing is I got all the values below 9999-12-31 as expected, so then why can I not get the values at 9999-12-31 to return? This is a very odd situation.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) <= 0
</code>```

Oddly enough that worked as it should have:

```<code>WHERE TERM_DT = '9999-12-31'
</code>```0

So I can get the dates below 9999-12-31 but cannot get the dates at 9999-12-31.
Once I realized that checking for dates lower than 9999-12-31 worked in the DATEDIFF() function I went back and tried to do my original comparison and check for those lesser dates. It worked...

```<code>WHERE TERM_DT = '9999-12-31'
</code>```1

Results:

```<code>WHERE TERM_DT = '9999-12-31'
</code>```2

With the above results there is no reason for me to think that WHERE TERM_DT = '9999-12-31' would not return:

```<code>DIFF        DT
3287        9999-12-31
3287        9999-12-31
</code>```

But I don't get that. I get no results at all.

Update:

I tried DATEDIFF(day, '9990-12-31', DH230.DH230_TERM_DT) <> 0 as @Ziad Mehmood mentioned and strangely I get all the negative values but none of the positive values.

```<code>DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
</code>```

2nd Update:

When I take my WHERE statement and move it to a CASE in the SELECT It clearly works. The Comparisons is correct. But just doesn't work in the WHERE section.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
,CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end
FROM ...
JOIN ...
</code>```

Results:

```<code>DIFF        DT  (No column name)
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2912261    2017-07-01  False
-2912352    2017-04-01  False
3287        9999-12-31  True
3287        9999-12-31  True
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2911852    2018-08-14  False
-2911852    2018-08-14  False
</code>```

So another shot in the dark I ran the CASE statement in the WHERE clause.

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'True'
</code>```

But no results:

```<code>DIFF        DT
</code>```

Now here is where it gets odd again:

```<code>WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'False'
</code>```

Returns:

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```0

Absolutely bizarre!

Is there some issue between SQL Server and a linked DB2 mainframe that could cause this?

Is there any know reason for something like this to happen?

I did create a local SQL Server table from a select statement to check the data type of the field.

The field is the DATE data type according to SSMS.

For a reference I have added my full query below with some obfuscation. Maybe something about the JOIN's is causing the problem.

```<code>INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'
</code>```1

答:
Please try some thing like this as seen the data

```<code>SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '2100-01-01', TERM_DT) <> 0
GROUP BY ...
</code>```

Hopefully this helps.

Body:
I have a very odd problem with a query I was given to convert from Access to SQL Server.

The query works as expected until I add a condition in the WHERE clause to check for a specific date.

I was not sure that the date fields were compatible due to the SQL Server query needing to talk to a linked DB2 mainframe. So to test this to make sure the date is being read correctly I used DATEDIFF(). I also reduced the select statement to only the date field that is having the issue to try and figure out what is going on but I still have had no luck. I have tried ever way I can think of to filter the date.

I tried a HAVING clause.

HAVING TERM_DT = '9999-12-31'

I tried a WHERE clause.

WHERE TERM_DT = '9999-12-31'

I tried to compare the date in the JOIN.

INNER JOIN linked_db2_tbl11 tbl11
    ON tbl11.TERM_DT = '9999-12-31'

I tried to CAST and CONVERT the field to DATE thinking maybe the date fields were incompatible.

CAST(TERM_DT AS DATE) = CAST('9999-12-31' AS DATE)
CONVERT(DATE, TERM_DT) = CONVERT(DATE, '9999-12-31')

In each of the above I also tried TERM_DT >= '9990-12-31' because nothing else worked and for some reason that column has a few typos like 9998-12-31 and 9999-11-31 so I figured checking from 9990 on should catch everything. Still nothing returned.

The last thing I tried was DATEDIFF(). And that didn't work either.

DATEDIFF(day, '9990-12-31', TERM_DT) >= 0

Except when I placed the DATEDIFF() in the select statement and do not use anything in the WHERE section I get the values I expect...

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...

Data returned:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30
3287        9999-12-31
3287        9999-12-31

But when I add the where statement in:

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) >= 0

I get no results:

DIFF        DT

Then I tried to flip the comparison with <= and the odd thing is I got all the values below 9999-12-31 as expected, so then why can I not get the values at 9999-12-31 to return? This is a very odd situation.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '9990-12-31', TERM_DT) <= 0

Oddly enough that worked as it should have:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

So I can get the dates below 9999-12-31 but cannot get the dates at 9999-12-31.
Once I realized that checking for dates lower than 9999-12-31 worked in the DATEDIFF() function I went back and tried to do my original comparison and check for those lesser dates. It worked...

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE TERM_DT < '9999-12-31'

Results:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

With the above results there is no reason for me to think that WHERE TERM_DT = '9999-12-31' would not return:

DIFF        DT
3287        9999-12-31
3287        9999-12-31

But I don't get that. I get no results at all.

Update:

I tried DATEDIFF(day, '9990-12-31', DH230.DH230_TERM_DT) <> 0 as @Ziad Mehmood mentioned and strangely I get all the negative values but none of the positive values.

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911852    2018-08-14
-2911852    2018-08-14
-2911624    2019-03-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911532    2019-06-30

2nd Update:

When I take my WHERE statement and move it to a CASE in the SELECT It clearly works. The Comparisons is correct. But just doesn't work in the WHERE section.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
,CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end
FROM ...
JOIN ...

Results:

DIFF        DT  (No column name)
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2912261    2017-07-01  False
-2912352    2017-04-01  False
3287        9999-12-31  True
3287        9999-12-31  True
-2911624    2019-03-30  False
-2911532    2019-06-30  False
-2911852    2018-08-14  False
-2911852    2018-08-14  False

So another shot in the dark I ran the CASE statement in the WHERE clause.

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'True'

But no results:

DIFF        DT

Now here is where it gets odd again:

WHERE CASE WHEN DH230.DH230_TERM_DT >'2100-12-31' THEN 'True' else 'False' end = 'False'

Returns:

DIFF        DT
-2912352    2017-04-01
-2912261    2017-07-01
-2911624    2019-03-30
-2911532    2019-06-30
-2911624    2019-03-30
-2911532    2019-06-30
-2911852    2018-08-14
-2911852    2018-08-14

Absolutely bizarre!

Is there some issue between SQL Server and a linked DB2 mainframe that could cause this?

Is there any know reason for something like this to happen?

I did create a local SQL Server table from a select statement to check the data type of the field.

The field is the DATE data type according to SSMS.

For a reference I have added my full query below with some obfuscation. Maybe something about the JOIN's is causing the problem.

SELECT DATEDIFF(day, '9990-12-31', linked_db2_tbl11.linked_db2_tbl11_TERM_DT) AS "DIFF"
,linked_db2_tbl11.linked_db2_tbl11_TERM_DT AS "DT"

FROM local_database.dbo.local_table1 IR
RIGHT JOIN linked_db2_tbl1
INNER JOIN linked_db2_tbl2
INNER JOIN linked_db2_tbl3
INNER JOIN linked_db2_tbl4
INNER JOIN linked_db2_tbl5
INNER JOIN linked_db2_tbl6
INNER JOIN linked_db2_tbl7
INNER JOIN linked_db2_tbl8
INNER JOIN linked_db2_tbl9
ON linked_db2_tbl8.linked_db2_tbl8_SUB_SVC_TYP = linked_db2_tbl9.linked_db2_tbl9_SUB_SVC_TYP
INNER JOIN linked_db2_tbl10
ON linked_db2_tbl9.linked_db2_tbl9_PACKAGE_ID = linked_db2_tbl10.linked_db2_tbl10_PACKAGE_ID
ON linked_db2_tbl7.linked_db2_tbl7_PACKAGE_ID = linked_db2_tbl10.linked_db2_tbl10_PACKAGE_ID
INNER JOIN linked_db2_tbl11
ON linked_db2_tbl9.linked_db2_tbl9_SVC_TYP = linked_db2_tbl11.linked_db2_tbl11_SVC_TYP
AND linked_db2_tbl9.linked_db2_tbl9_PACKAGE_ID = linked_db2_tbl11.linked_db2_tbl11_PACKAGE_ID
ON linked_db2_tbl6.linked_db2_tbl6_COMP_ID = linked_db2_tbl7.linked_db2_tbl7_COMP_ID
AND linked_db2_tbl6.linked_db2_tbl6_COMP_ID = linked_db2_tbl11.linked_db2_tbl11_COMP_ID
ON linked_db2_tbl5.linked_db2_tbl5_COMP_ID = linked_db2_tbl6.linked_db2_tbl6_COMP_ID
ON linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID = linked_db2_tbl5.linked_db2_tbl5_ELEMENT_ID
AND linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID = linked_db2_tbl11.linked_db2_tbl11_ELEMENT_ID
ON linked_db2_tbl3.linked_db2_tbl3_ELEMENT_ID = linked_db2_tbl4.linked_db2_tbl4_ELEMENT_ID
AND linked_db2_tbl3.linked_db2_tbl3_CHG_CD = linked_db2_tbl11.linked_db2_tbl11_CHG_CD
ON linked_db2_tbl2.linked_db2_tbl2_CHG_CD = linked_db2_tbl3.linked_db2_tbl3_CHG_CD
ON linked_db2_tbl1.linked_db2_tbl1_SUB_SVC_TYP = linked_db2_tbl8.linked_db2_tbl8_SUB_SVC_TYP
AND linked_db2_tbl1.linked_db2_tbl1_HWIR_SVC_TYP = linked_db2_tbl8.linked_db2_tbl8_HWIR_SVC_TYP
AND linked_db2_tbl1.linked_db2_tbl1_SVC_ID = linked_db2_tbl11.linked_db2_tbl11_LEVEL_ID
INNER JOIN linked_db2_tbl12
INNER JOIN linked_db2_tbl13
ON linked_db2_tbl12.linked_db2_tbl12_RATE_PLAN = linked_db2_tbl13.linked_db2_tbl13_RATE_PLAN
ON linked_db2_tbl1.linked_db2_tbl1_SVC_ID = linked_db2_tbl13.linked_db2_tbl13_SVC_ID
INNER JOIN linked_db2_tbl14
ON linked_db2_tbl1.linked_db2_tbl1_UPPER_ID = linked_db2_tbl14.linked_db2_tbl14_CORP_ID
ON IR.CHG_CD = linked_db2_tbl11.linked_db2_tbl11_CHG_CD
LEFT JOIN linked_db2_tbl15
ON linked_db2_tbl14.linked_db2_tbl14_CORP_ID = linked_db2_tbl15.linked_db2_tbl15_INT_ID
INNER JOIN linked_db2_tbl18
ON linked_db2_tbl1.linked_db2_tbl1_CNTL_LOCN_ID = linked_db2_tbl18.linked_db2_tbl18_COMS_LOCN_ID
JOIN local_database.dbo.local_table2 OT
ON linked_db2_tbl14.linked_db2_tbl14_CORP_ID = OT.CORP_ID
WHERE OT.USER_ID = 'SOMEID'
AND DATEDIFF(day, '9990-12-31', linked_db2_tbl11.linked_db2_tbl11_TERM_DT) >= 0

Body:
Please try some thing like this as seen the data

SELECT DATEDIFF(day, '9990-12-31', TERM_DT) AS "DIFF"
,TERM_DT AS "DT"
FROM ...
JOIN ...
WHERE DATEDIFF(day, '2100-01-01', TERM_DT) <> 0
GROUP BY ...

Hopefully this helps.


问:
Sum of a series using for loop in C
I am a complete beginner in C and learning to code on my own using the internet and i have written the following code to find the sum of the series
s= 1/1 + 2^2/2 + 3^3/3 .........
using the for loop in c.
Here is the code:

```<code>#include<stdio.h>
#include<math.h>
int main()
{
     int i,n;
     float a,b;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(i=1;i<=n;i++)
     {
          a=pow(i,i)/i;
          b=a+a;
     }
     printf("The sum of the series is %f\n",b);
     return 0;
}
</code>```

I am pretty sure that i am making a logical error but i seem to be too dumb or slow to figure that out so i would appreciate for someone to point that out for me. Thank you :)

答:
mm, you missed one part, which is adding the output of the current calculation to the total sum.

This statement:

```<code>b=a+a
</code>```

Will give 'b' the value of a + a, so when passing 4 as a input argument the b will have the following values:

```<code>b = 1 + 1
b = 2 + 2
b = 9 + 9
b = 64 + 64
</code>```

This can be fixed by adding the value to the total sum:

```<code>#include<stdio.h>
#include<math.h>
int main()
{
     int n;
     float sum = 0;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(int i=1;i<=n;i++)
     {
          float a = pow(i,i)/i;
          sum += a;
     }
     printf("The sum of the series is %f\n", sum);
     return 0;
}
</code>```

Which gives me the following output:

```<code>Enter the number of terms in the series:
4
The sum of the series is 76.000000
</code>```

Title: Sum of a series using for loop in C

Body:
I am a complete beginner in C and learning to code on my own using the internet and i have written the following code to find the sum of the series
s= 1/1 + 2^2/2 + 3^3/3 .........
using the for loop in c.
Here is the code:

#include<stdio.h>
#include<math.h>
int main()
{
     int i,n;
     float a,b;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(i=1;i<=n;i++)
     {
          a=pow(i,i)/i;
          b=a+a;
     }
     printf("The sum of the series is %f\n",b);
     return 0;
}

I am pretty sure that i am making a logical error but i seem to be too dumb or slow to figure that out so i would appreciate for someone to point that out for me. Thank you :)

Body:
mm, you missed one part, which is adding the output of the current calculation to the total sum.

This statement:

b=a+a

Will give 'b' the value of a + a, so when passing 4 as a input argument the b will have the following values:

b = 1 + 1
b = 2 + 2
b = 9 + 9
b = 64 + 64

This can be fixed by adding the value to the total sum:

#include<stdio.h>
#include<math.h>
int main()
{
     int n;
     float sum = 0;
     printf("Enter the number of terms in the series: \n");
     scanf("%i",&n);
     for(int i=1;i<=n;i++)
     {
          float a = pow(i,i)/i;
          sum += a;
     }
     printf("The sum of the series is %f\n", sum);
     return 0;
}

Which gives me the following output:

Enter the number of terms in the series:
4
The sum of the series is 76.000000


问:
How can we create Boolean-like object in JavaScript?
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

```<code>MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}
</code>```

and its instances

```<code>mytrue = new MyBool(true);
myfalse = new MyBool(false);
</code>```

But now, I noticed that

```<code>if (myfalse) {
  console.log ("myfalse is true!!!")
}
</code>```

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

```<code>undefined, null, false, +0, -0, NaN, ''
</code>```

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

```<code>myfalse.constructor is MyBool
(!! myfalse) is false
</code>```

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.

答:
In response to your comment, indicating you want a strict boolean. Why not use the equality operator?</p>

```<code>var someBoolean = false,
    someObj = { };

if (someBoolean === false)
{
    // tada, someBoolean is a boolean AND false
}

// Returns false because someObj is NOT a boolean
if (someObj === true)
{
   ..
}
</code>```

Body:
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}

and its instances

mytrue = new MyBool(true);
myfalse = new MyBool(false);

But now, I noticed that

if (myfalse) {
  console.log ("myfalse is true!!!")
}

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

undefined, null, false, +0, -0, NaN, ''

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

myfalse.constructor is MyBool
(!! myfalse) is false

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.

Body:
In response to your comment, indicating you want a strict boolean. Why not use the equality operator?

var someBoolean = false,
    someObj = { };

if (someBoolean === false)
{
    // tada, someBoolean is a boolean AND false
}

// Returns false because someObj is NOT a boolean
if (someObj === true)
{
   ..
}


问:
QML FileDialog Assertion failed
I'm trying to use the FileDialog. but when I browse at the second time
I got a crash with information is

"Gtk: Error assertion failed: (cancellable == data->button_data->cancellable)"

How do I address this problem?

答:
Qt5 can uses native file dialog from your desktop environment. There is some bug in a connection between Qt and GTK.
Looks like the same as
https://github.com/tkashkin/GameHub/issues/76</p>

Title: QML FileDialog Assertion failed


问:
Combine multiple variables into new variable / Split Variable into 3 variables
I need to create a 'key' variable, since I want to combine two datasets.

Dataset1 has the variable ymd.

Dataset2 has the three variables y, m and d.

```<code>ymd  (20050516,20060512)
y(2005,2006)
m(05,05)
d(16,12)
</code>```

Two Options:

Combine y,m and d into variable ymd

List item plit variable ymd into 3 variables y, m and d.

答:
Assuming you have two data frames:

```<code>df1 <- data.frame(
  ymd = c(20050516,20060512),
  x = c(1,2)
)

df2 <- data.frame(
  y = c(2005,2006),
  m = c('05','05'),
  d = c(16,12),
  z = c(5,10)
)
</code>```

You can merge by pasting together the y, m, and d elements using paste0 and changing to numeric:

```<code>df2 %>%
  mutate(
    ymd = as.numeric(paste0(y,m,d))
  ) %>%
  left_join(df1)
</code>```

Output:

```<code>>
Joining, by = "ymd"
     y  m  d  z      ymd x
1 2005 05 16  5 20050516 1
2 2006 05 12 10 20060512 2
</code>```

You can adjust the merge (eg right_join) depending on your needs.

Body:
I need to create a 'key' variable, since I want to combine two datasets.

Dataset1 has the variable ymd.

Dataset2 has the three variables y, m and d.

ymd  (20050516,20060512)
y(2005,2006)
m(05,05)
d(16,12)

Two Options:

Combine y,m and d into variable ymd

List item plit variable ymd into 3 variables y, m and d.

Body:
Assuming you have two data frames:

df1 <- data.frame(
  ymd = c(20050516,20060512),
  x = c(1,2)
)

df2 <- data.frame(
  y = c(2005,2006),
  m = c('05','05'),
  d = c(16,12),
  z = c(5,10)
)

You can merge by pasting together the y, m, and d elements using paste0 and changing to numeric:

df2 %>%
  mutate(
    ymd = as.numeric(paste0(y,m,d))
  ) %>%
  left_join(df1)

Output:

>
Joining, by = "ymd"
     y  m  d  z      ymd x
1 2005 05 16  5 20050516 1
2 2006 05 12 10 20060512 2

You can adjust the merge (eg right_join) depending on your needs.


问:
how can I send a data by ajax and the url has a variable value in the middle of the link
I am using this API:'/api/categories/${catID}/items/addItem/'

from my spring boot java to enter some data to item table which has relation with category table.

Now in javascript, I used ajax:
$.ajax({
        url: '/api/categories/${catID}/items/addItem/',
         type: "POST",
        contentType: "application/json",
        etc

Now I get a problem from the url and cannot read the value of ${catID}

This is the real API: "/api/categories/{categoryId}/items/addItem"
I have looked inside the site but the solution does not work with me.
Now how can I pass a value of a variable if the variable are in the middle.

Thanks in advance.

答:
You're trying to use template literals which require backticks(`) instead of single quotes(').</p>

```<code>url: `/api/categories/${catID}/items/addItem/`
</code>```

Body:
You're trying to use template literals which require backticks(`) instead of single quotes(').

url: `/api/categories/${catID}/items/addItem/`


问:
matlab, format table nicely, without cell arrays
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

```<code>t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}
</code>```

答:
You can't get rid of '' or "", but you can use strings instead of character vectors for a better formatted table display:

```<code>>> t = {"a","b","c"}

t =
  1×3 cell array
   {["a"]}    {["b"]}    {["c"]}

>> cell2table(t,'VariableNames',{'1','2','3'})

ans =
  1×3 table

     1      2      3
    ___    ___    ___

    "a"    "b"    "c"
</code>```

Body:
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}

Body:
You can't get rid of '' or "", but you can use strings instead of character vectors for a better formatted table display:

>> t = {"a","b","c"}

t =
  1×3 cell array
   {["a"]}    {["b"]}    {["c"]}

>> cell2table(t,'VariableNames',{'1','2','3'})

ans =
  1×3 table

     1      2      3
    ___    ___    ___

    "a"    "b"    "c"


问:
Trying to create email log system but array stays blank
So I'm trying to create some sort of email log system with the subject and message previewed on each line, like gmail.

In mainWindowScript.py, I have a 'compose' button that appends a string to an array in getLogs.py, and a 'logs' button that runs getLogs.py using the os module. In getLogs.py, I just have a ListBox. I used tkinter to create buttons and listboxes.

When I run mainWindowScript.py, it first opens the listbox created in getLogs.py which isn't supposed to happen. But the weird part is when I close that window and click my 'compose' button, the list I tried to append to is still empty, making the listbox empty.

It's really confusing I need help.

Here is mainWindowScript.py:

```<code>import tkinter as tk
from tkinter import ttk
import os

import getLogs as gl

mainWin = tk.Tk()

canvas = tk.Canvas(mainWin, width = 400, height = 400)
canvas.pack()

frame = tk.Frame(mainWin, bg = "gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

def compose():
    gl.tos.append("isybgf")
    #os.system("python email_gui.py")            #run another python file

def getEmailLogs():
    os.system("python getLogs.py")

composeButton = tk.Button(frame, bg = "blue", fg = "white", text = "COMPOSE", command = compose)
composeButton.place(relx = 0.3, rely = 0.2, relwidth = 0.4, relheight = 0.2)

logsButton = tk.Button(frame, bg = "blue", fg = "white", text = "LOGS", command = getEmailLogs)
logsButton.place(relx = 0.3, rely = 0.5, relwidth = 0.4, relheight = 0.2)

mainWin.mainloop()
</code>```

And getLogs.py:

```<code>import tkinter as tk

mainWind = tk.Tk()

canvas = tk.Canvas(mainWind, width = 400, height = 600)
canvas.pack()

frame = tk.Frame(mainWind, bg = "gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

mailLogs = tk.Listbox(frame)
mailLogs.place(relx = 0.1, rely = 0.05, relwidth = 0.8, relheight = 0.9)

tos = []
subjects = []
messages = []

print(tos)

mails = {
    "to:": tos,
    "subject:": subjects,
    "message:": messages
}

for i in range(0, len(tos)):
    emailLogTitle = "{}: {} - {}".format(mails["to:"][i], mails["subject:"][i], mails["message:"][i])
    mailLogs.insert('end', emailLogTitle)

mainWind.mainloop()
</code>```

答:
Using os.system() you run separated program which has no access to data create in current program. Because you import getLogs so you should put code in function to execute it without os.system()

getLogs.py

```<code>import tkinter as tk

tos = []
subjects = []
messages = []

def log_window():

    #mainWind = tk.Tk()
    mainWind = tk.Toplevel()

    canvas = tk.Canvas(mainWind, width = 400, height = 600)
    canvas.pack()

    frame = tk.Frame(mainWind, bg = "gray")
    frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

    mailLogs = tk.Listbox(frame)
    mailLogs.place(relx = 0.1, rely = 0.05, relwidth = 0.8, relheight = 0.9)

    print(tos)

    mails = {
        "to:": tos,
        "subject:": subjects,
        "message:": messages
    }

    for i in range(0, len(tos)):
        emailLogTitle = "{}: {} - {}".format(mails["to:"][i], mails["subject:"][i], mails["message:"][i])
        mailLogs.insert('end', emailLogTitle)

    #mainWind.mainloop()
</code>```

And now you can execute it

```<code>def getEmailLogs():
    gl.log_window()
</code>```

and it will have access to values in tos

Because both windows run in the same program so second doesn't need mainloop() and it should be created by Toplevel(), not Tk()

BTW: composer was adding only tos so later dictionary mail was no subjects and messages. You could rather create one list with mails instead of separated list for to,  subject, message

mai.py

```<code>import tkinter as tk
import os

import getLogs as gl

# --- functions ---

def compose():
    gl.tos.append("isybgf")
    gl.subjects.append("isybgf")
    gl.messages.append("isybgf")
    # it could be better to keep it in one list ie.
    # mails.append( {'to': "isybgf", 'subject': "isybgf", 'message': "isybgf" } )

def getEmailLogs():
    gl.log_window()

# --- main ---

mainWin = tk.Tk()

canvas = tk.Canvas(mainWin, width=400, height=400)
canvas.pack()

frame = tk.Frame(mainWin, bg="gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

composeButton = tk.Button(frame, bg="blue", fg="white", text="COMPOSE", command=compose)
composeButton.place(relx=0.3, rely=0.2, relwidth=0.4, relheight=0.2)

logsButton = tk.Button(frame, bg="blue", fg="white", text="LOGS", command=getEmailLogs)
logsButton.place(relx=0.3, rely=0.5, relwidth=0.4, relheight=0.2)

mainWin.mainloop()
</code>```

EDIT: Version with other changes - reduced to important elements. I keep mails on one list mails in main program and send to log as argument.

main.py

```<code>import tkinter as tk
import getLogs as gl

# --- functions ---

def compose():
    mails.append( {'to': "user@domain.com", 'subject': "Read it", 'message': "Hello World!"} )

def get_email_logs():
    gl.log_window(mails)

# --- main --- (lower_case_names)

mails = []

main_window = tk.Tk()

compose_button = tk.Button(main_window, text="COMPOSE", command=compose)
compose_button.pack(fill='x')

logs_button = tk.Button(main_window, text="LOGS", command=get_email_logs)
logs_button.pack(fill='x')

close_button = tk.Button(main_window, text="CLOSE", command=main_window.destroy)
close_button.pack(fill='x')

main_window.mainloop()
</code>```

getLogs.py

```<code>import tkinter as tk

def log_window(mails):

    window = tk.Toplevel()

    mail_logs = tk.Listbox(window)
    mail_logs.pack(fill='both', expand=True)

    close_button = tk.Button(window, text="CLOSE", command=window.destroy)
    close_button.pack(fill='x')

    for item in mails:
        mail_logs.insert('end', "{}: {} - {}".format( item["to"], item["subject"], item["message"] ))
</code>```

Body:
So I'm trying to create some sort of email log system with the subject and message previewed on each line, like gmail.

In mainWindowScript.py, I have a 'compose' button that appends a string to an array in getLogs.py, and a 'logs' button that runs getLogs.py using the os module. In getLogs.py, I just have a ListBox. I used tkinter to create buttons and listboxes.

When I run mainWindowScript.py, it first opens the listbox created in getLogs.py which isn't supposed to happen. But the weird part is when I close that window and click my 'compose' button, the list I tried to append to is still empty, making the listbox empty.

It's really confusing I need help.

Here is mainWindowScript.py:

import tkinter as tk
from tkinter import ttk
import os

import getLogs as gl

mainWin = tk.Tk()

canvas = tk.Canvas(mainWin, width = 400, height = 400)
canvas.pack()

frame = tk.Frame(mainWin, bg = "gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

def compose():
    gl.tos.append("isybgf")
    #os.system("python email_gui.py")            #run another python file

def getEmailLogs():
    os.system("python getLogs.py")

composeButton = tk.Button(frame, bg = "blue", fg = "white", text = "COMPOSE", command = compose)
composeButton.place(relx = 0.3, rely = 0.2, relwidth = 0.4, relheight = 0.2)

logsButton = tk.Button(frame, bg = "blue", fg = "white", text = "LOGS", command = getEmailLogs)
logsButton.place(relx = 0.3, rely = 0.5, relwidth = 0.4, relheight = 0.2)

mainWin.mainloop()

And getLogs.py:

import tkinter as tk

mainWind = tk.Tk()

canvas = tk.Canvas(mainWind, width = 400, height = 600)
canvas.pack()

frame = tk.Frame(mainWind, bg = "gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

mailLogs = tk.Listbox(frame)
mailLogs.place(relx = 0.1, rely = 0.05, relwidth = 0.8, relheight = 0.9)

tos = []
subjects = []
messages = []

print(tos)

mails = {
    "to:": tos,
    "subject:": subjects,
    "message:": messages
}

for i in range(0, len(tos)):
    emailLogTitle = "{}: {} - {}".format(mails["to:"][i], mails["subject:"][i], mails["message:"][i])
    mailLogs.insert('end', emailLogTitle)

mainWind.mainloop()

Body:
Using os.system() you run separated program which has no access to data create in current program. Because you import getLogs so you should put code in function to execute it without os.system()

getLogs.py

import tkinter as tk

tos = []
subjects = []
messages = []

def log_window():

    #mainWind = tk.Tk()
    mainWind = tk.Toplevel()

    canvas = tk.Canvas(mainWind, width = 400, height = 600)
    canvas.pack()

    frame = tk.Frame(mainWind, bg = "gray")
    frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

    mailLogs = tk.Listbox(frame)
    mailLogs.place(relx = 0.1, rely = 0.05, relwidth = 0.8, relheight = 0.9)

    print(tos)

    mails = {
        "to:": tos,
        "subject:": subjects,
        "message:": messages
    }

    for i in range(0, len(tos)):
        emailLogTitle = "{}: {} - {}".format(mails["to:"][i], mails["subject:"][i], mails["message:"][i])
        mailLogs.insert('end', emailLogTitle)

    #mainWind.mainloop()

And now you can execute it

def getEmailLogs():
    gl.log_window()

and it will have access to values in tos

Because both windows run in the same program so second doesn't need mainloop() and it should be created by Toplevel(), not Tk()

BTW: composer was adding only tos so later dictionary mail was no subjects and messages. You could rather create one list with mails instead of separated list for to,  subject, message

mai.py

import tkinter as tk
import os

import getLogs as gl

# --- functions ---

def compose():
    gl.tos.append("isybgf")
    gl.subjects.append("isybgf")
    gl.messages.append("isybgf")
    # it could be better to keep it in one list ie.
    # mails.append( {'to': "isybgf", 'subject': "isybgf", 'message': "isybgf" } )

def getEmailLogs():
    gl.log_window()

# --- main ---

mainWin = tk.Tk()

canvas = tk.Canvas(mainWin, width=400, height=400)
canvas.pack()

frame = tk.Frame(mainWin, bg="gray")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)

composeButton = tk.Button(frame, bg="blue", fg="white", text="COMPOSE", command=compose)
composeButton.place(relx=0.3, rely=0.2, relwidth=0.4, relheight=0.2)

logsButton = tk.Button(frame, bg="blue", fg="white", text="LOGS", command=getEmailLogs)
logsButton.place(relx=0.3, rely=0.5, relwidth=0.4, relheight=0.2)

mainWin.mainloop()

EDIT: Version with other changes - reduced to important elements. I keep mails on one list mails in main program and send to log as argument.

main.py

import tkinter as tk
import getLogs as gl

# --- functions ---

def compose():
    mails.append( {'to': "user@domain.com", 'subject': "Read it", 'message': "Hello World!"} )

def get_email_logs():
    gl.log_window(mails)

# --- main --- (lower_case_names)

mails = []

main_window = tk.Tk()

compose_button = tk.Button(main_window, text="COMPOSE", command=compose)
compose_button.pack(fill='x')

logs_button = tk.Button(main_window, text="LOGS", command=get_email_logs)
logs_button.pack(fill='x')

close_button = tk.Button(main_window, text="CLOSE", command=main_window.destroy)
close_button.pack(fill='x')

main_window.mainloop()

getLogs.py

import tkinter as tk

def log_window(mails):

    window = tk.Toplevel()

    mail_logs = tk.Listbox(window)
    mail_logs.pack(fill='both', expand=True)

    close_button = tk.Button(window, text="CLOSE", command=window.destroy)
    close_button.pack(fill='x')

    for item in mails:
        mail_logs.insert('end', "{}: {} - {}".format( item["to"], item["subject"], item["message"] ))


问:
Passing an array through params as multiple parameters
If I have a method like this:

```<code>Foo(params string[] parameters)
</code>```

I would like to pass in both "regular parameters" and an array in a single call like this:

```<code>string[] myArray = new[] { "param3", "param4" };
Foo("param1", "param2", myArray);
</code>```

such that it is equivalent to this:

```<code>Foo("param1", "param2", "param3", "param4");
</code>```

Is there a function I can call on the array or some sort of way that I can modify my Foo method? Currently I'm doing something like this:

```<code>string[] myArray = new[] { "param3", "param4" };
List<string> arguments = new List<string>
{
  "param1",
  "param2"
};
arguments.AddRange(myArray);
Foo(arguments.ToArray());
</code>```

but I'm wondering if there's a better way

答:
One concise way to pass all your paramters would look like this:</p>

```<code>string[] myArray = new[] { "param3", "param4" };
Foo(new[] { "param1", "param2" }.Concat(myArray).ToArray());
</code>```

Body:
If I have a method like this:

Foo(params string[] parameters)

I would like to pass in both "regular parameters" and an array in a single call like this:

string[] myArray = new[] { "param3", "param4" };
Foo("param1", "param2", myArray);

such that it is equivalent to this:

Foo("param1", "param2", "param3", "param4");

Is there a function I can call on the array or some sort of way that I can modify my Foo method? Currently I'm doing something like this:

string[] myArray = new[] { "param3", "param4" };
List<string> arguments = new List<string>
{
  "param1",
  "param2"
};
arguments.AddRange(myArray);
Foo(arguments.ToArray());

but I'm wondering if there's a better way

Body:
One concise way to pass all your paramters would look like this:

string[] myArray = new[] { "param3", "param4" };
Foo(new[] { "param1", "param2" }.Concat(myArray).ToArray());


问:
Android, icon been duplicate when i install my app on the device
I try to install the app that i develop on my device  (Htc desire) and i see that the icon of the app is duplicate

what i need to change to don't late that happen?

how could i delete one of the icon?

Thanks for helping!!

答:
do you use the default icone of android , or u have change the app's icon from the manifest ? </p>

<p>if that's right , try using the default icon of android , and then see if that will duplicate the app's icon or not </p>

Body:
do you use the default icone of android , or u have change the app's icon from the manifest ?

if that's right , try using the default icon of android , and then see if that will duplicate the app's icon or not


问:
Can you stop unused static objects from being constructed?
When I link a file that contains a static object, that object's constructor is ran regardless of whether the object is ever used or the header is even included. Is there a way in g++ to stop this behavior from occurring, or is the only answer to just not link the file?

foo.h

```<code>#include <iostream>

class Bar {
public:
    Bar(int inMemberInt) {
        std::cout << "In Bar constructor." << std::endl;
    }
};

class Foo {
public:
    static const Bar constVar;
};
</code>```

foo.cpp

```<code>#include "foo.h"

const Bar Foo::constVar(1);
</code>```

main.cpp

```<code>#include <iostream>

int main() {
    std::cout << "Hello." << std::endl;

    return 1;
}
</code>```

Build command

```<code>g++ foo.h foo.cpp main.cpp -o main
</code>```

Output

```<code>In Bar constructor.
Hello.
</code>```

答:
You can make the class a template (probably with defaulted template parameter) and then the static data member's definition will be instantiated only when (odr-)used somewhere in the program.

This requires you to move the definition of the class members into the header, though. If this is too large of an impact, you might want to consider putting the static member in a base class that is a class template, which will have the same effect as making the whole class a template as long as you don't reference the static member anywhere. The static member's definition will need to be moved to the header in any case (explicit instantiation would counter the intended effect.)

This doesn't mean though that, if the static member is (odr-)used, the initializer will run only when the variable is used the first time in the program run. Whether that is the case or not is implementation-defined.

The alternative that guarantees not only that the initializer is never run when the variable isn't used in the program code, but also guarantees that it is run exactly when it is used the first time, is to use a local static variable in a static member function instead:

```<code>static const Bar& constVar() {
    static const Bar instance(1);
    return instance;
};
</code>```

Then use it as constVar() instead of constVar. (The definition of the function can also be out-of-class.) This does however come with a performance penalty, because the implementation of local statics must be thread-safe.

Body:
When I link a file that contains a static object, that object's constructor is ran regardless of whether the object is ever used or the header is even included. Is there a way in g++ to stop this behavior from occurring, or is the only answer to just not link the file?

foo.h

#include <iostream>

class Bar {
public:
    Bar(int inMemberInt) {
        std::cout << "In Bar constructor." << std::endl;
    }
};

class Foo {
public:
    static const Bar constVar;
};

foo.cpp

#include "foo.h"

const Bar Foo::constVar(1);

main.cpp

#include <iostream>

int main() {
    std::cout << "Hello." << std::endl;

    return 1;
}

Build command

g++ foo.h foo.cpp main.cpp -o main

Output

In Bar constructor.
Hello.

Body:
You can make the class a template (probably with defaulted template parameter) and then the static data member's definition will be instantiated only when (odr-)used somewhere in the program.

This requires you to move the definition of the class members into the header, though. If this is too large of an impact, you might want to consider putting the static member in a base class that is a class template, which will have the same effect as making the whole class a template as long as you don't reference the static member anywhere. The static member's definition will need to be moved to the header in any case (explicit instantiation would counter the intended effect.)

This doesn't mean though that, if the static member is (odr-)used, the initializer will run only when the variable is used the first time in the program run. Whether that is the case or not is implementation-defined.

The alternative that guarantees not only that the initializer is never run when the variable isn't used in the program code, but also guarantees that it is run exactly when it is used the first time, is to use a local static variable in a static member function instead:

static const Bar& constVar() {
    static const Bar instance(1);
    return instance;
};

Then use it as constVar() instead of constVar. (The definition of the function can also be out-of-class.) This does however come with a performance penalty, because the implementation of local statics must be thread-safe.


答:
Here you have an example.

I use the variables as string instead of numeric, which makes it easier. You can use as.character() as in my example to convert it.

For option 1, I just use paste0() to paste the text together.

For option 2 I use substr() to cut the text in the corect locations.

If you need the output as numeric and not string, just use as.numeric() as I did in the print function.

Here is the code, let me know if you have further question:

```<code>ymd=as.character(c(20050516,20060512))
y=as.character(c(2005,2006))
m=as.character(c(05,05))
d=as.character(c(16,12))

## Concatenade y, m, and d together
ymd_concatenated=paste0(y,m,d)
print(as.numeric(ymd_concatenated))

## Split ymd into single variables
y_concatenated=c()
m_concatenated=c()
d_concatenated=c()
for (date in ymd)
{
  y_concatenated=c(y_concatenated,substr(date,1,4))
  m_concatenated=c(m_concatenated,substr(date,5,6))
  d_concatenated=c(d_concatenated,substr(date,7,8))
}
print(y_concatenated)
print(m_concatenated)
print(d_concatenated)
</code>```

Title: Combine multiple variables into new variable / Split Variable into 3 variables

Body:
Here you have an example.

I use the variables as string instead of numeric, which makes it easier. You can use as.character() as in my example to convert it.

For option 1, I just use paste0() to paste the text together.

For option 2 I use substr() to cut the text in the corect locations.

If you need the output as numeric and not string, just use as.numeric() as I did in the print function.

Here is the code, let me know if you have further question:

ymd=as.character(c(20050516,20060512))
y=as.character(c(2005,2006))
m=as.character(c(05,05))
d=as.character(c(16,12))

## Concatenade y, m, and d together
ymd_concatenated=paste0(y,m,d)
print(as.numeric(ymd_concatenated))

## Split ymd into single variables
y_concatenated=c()
m_concatenated=c()
d_concatenated=c()
for (date in ymd)
{
  y_concatenated=c(y_concatenated,substr(date,1,4))
  m_concatenated=c(m_concatenated,substr(date,5,6))
  d_concatenated=c(d_concatenated,substr(date,7,8))
}
print(y_concatenated)
print(m_concatenated)
print(d_concatenated)


问:
in spyder IDE, run selection works fine, run file keeps running/ hangs
in Spyder IDE, the run selection command (F9) works fine. the run file command (F5) keeps running for hours, without outputs except

In [1]: runfile('...\MyFolder\MyScrip.py', wdir='...\MyFolder')

until I restart the kernel.

already seen this questions (same, without useful answers)

Spider Run button doesn't behave as expected

Spyder: different results depending on if I run code with F5 or F9

my script is:

```<code>import edgar as edg
edg.download_index(r'D:\SEC',2019)
</code>```

where "edgar" is python-edgar (pip).

I used another package, by pip, called edgar, which is always imported as "edgar".

They were installed toghether, so a though about a conflict, and I removed both and reainstalled just python-edgar. Totally useless!

答:
Faced the  similar issue in Spyder IDE (3.3.4.) and Windows10. Took half hour to wait in the first try and returned nothing for waiting hours since the second try.

But everything is just fine now in my case, took just a few seconds to download all files when using PowerShell.

Python run.py -y 1993

Body:
in Spyder IDE, the run selection command (F9) works fine. the run file command (F5) keeps running for hours, without outputs except

In [1]: runfile('...\MyFolder\MyScrip.py', wdir='...\MyFolder')

until I restart the kernel.

already seen this questions (same, without useful answers)

Spider Run button doesn't behave as expected

Spyder: different results depending on if I run code with F5 or F9

my script is:

import edgar as edg
edg.download_index(r'D:\SEC',2019)

where "edgar" is python-edgar (pip).

I used another package, by pip, called edgar, which is always imported as "edgar".

They were installed toghether, so a though about a conflict, and I removed both and reainstalled just python-edgar. Totally useless!


问:
Jhipster JDL relationships. Relation between two entities, Entity A is one to many with two columns seperately in entity B
Entity A: Person,
Entity B: Payment (columns: effectiveDate, fromPerson, toPerson).
Person should be one to many with both fromPerson and to Person so that I can track payer and payee.

This is how I have defined them in jdl file which is not working as desired.

```<code>entity Person {
  firstName String maxlength(100)
  lastName String maxlength(100)
}
entity Payment{
  effectiveDate Instant
  paymentRefNumber String
  amount Double
}

relationship OneToMany {
  Person to Payment{fromParty}
  Person to Payment{toParty}
}
</code>```

When I generate code with this jdl file, I am getting error in person pojos where the relationships are defined twice and when I rectify them, application is taking too long to start about 30 mins

Any idea where I am going wrong?

My jdl file configuration:

```<code>application {
  config {
    databaseType sql
    devDatabaseType postgresql
    enableHibernateCache true
    enableSwaggerCodegen false
    enableTranslation true
    jhiPrefix sys
    languages [en, bn, hi, mr, ta, te]
    nativeLanguage en
    packageName com.eezibizi
    prodDatabaseType postgresql
    serviceDiscoveryType false
    skipClient false
    skipServer false
    testFrameworks [gatling, cucumber, protractor]
    websocket spring-websocket
    applicationType monolith
    baseName eezibizi
    serverPort 8080
    authenticationType session
    cacheProvider hazelcast
    buildTool gradle
    useSass true
    clientPackageManager npm
    clientFramework react
  }
  entities *
}
</code>```

If there is a better approach, please suggest

答:
The problem is that you have two relationships from Person to Payment but you did not specify a relationship name for any of them. The default name will be used for both (payments I guess) leaving you with two fields having the same name, and this is incorrect for obvious reasons.

Give them names and everything should be generated correctly.

relationship OneToMany {
  Person{outgoingPayments} to Payment{fromPerson}
  Person{incomingPayments} to Payment{toPerson}
}
```

Body:
Entity A: Person,
Entity B: Payment (columns: effectiveDate, fromPerson, toPerson).
Person should be one to many with both fromPerson and to Person so that I can track payer and payee.

This is how I have defined them in jdl file which is not working as desired.

entity Person {
  firstName String maxlength(100)
  lastName String maxlength(100)
}
entity Payment{
  effectiveDate Instant
  paymentRefNumber String
  amount Double
}

relationship OneToMany {
  Person to Payment{fromParty}
  Person to Payment{toParty}
}

When I generate code with this jdl file, I am getting error in person pojos where the relationships are defined twice and when I rectify them, application is taking too long to start about 30 mins

Any idea where I am going wrong?

My jdl file configuration:

application {
  config {
    databaseType sql
    devDatabaseType postgresql
    enableHibernateCache true
    enableSwaggerCodegen false
    enableTranslation true
    jhiPrefix sys
    languages [en, bn, hi, mr, ta, te]
    nativeLanguage en
    packageName com.eezibizi
    prodDatabaseType postgresql
    serviceDiscoveryType false
    skipClient false
    skipServer false
    testFrameworks [gatling, cucumber, protractor]
    websocket spring-websocket
    applicationType monolith
    baseName eezibizi
    serverPort 8080
    authenticationType session
    cacheProvider hazelcast
    buildTool gradle
    useSass true
    clientPackageManager npm
    clientFramework react
  }
  entities *
}

If there is a better approach, please suggest


问:
Make modal open after request - Vue.js
i have a register modal with vuejs and i need if user inserted the wrong information in the form and the information didn't validated in controller (using laravel) i could redirect user to the same page with modal open (i have "showRegister" in data and i need to make it open with "showRegister : true" after redirect)

```<code>    new Vue({
        el: '.LR-PC',
        data: {
            showRegister: false,
            showLogin:false,
        }
    });
</code>```

on default when we redirect to page showRegister is false

code:

```<code>                <script type="text/x-template" id="modal-template">
                    <transition name="modal">
                        <div class="modal-mask">
                            <div class="modal-wrapper">
                                <div class="modal-container">
                                    <div class="modal-header">
                                        <i class="fa fa-window-close" @click="$emit('close')" style="margin : 0 0 0 100%;"></i>
                                        <slot name="header">
                                            create user
                                        </slot>
                                    </div>
                                            <div class="modal-body">
                                                <slot name="body">
                                            <form method="POST" action="{{ route('register') }}">
                                                @csrf
                                            <input class="input-style-1"  type="text" name="name" id="name" maxlength="9"/>
                                            <input  class="input-style-1"  type="text" name="f-name" id="f-name" maxlength="10"/>
                                            <input class="input-style-1" type="email" name="email" maxlength="50">
                                            <input name="password" class="input-style-1" type="password" maxlength="18">
                                            <input type="password" name="password_confirmation" class="input-style-1" maxlength="18" onchange="hi(sa)">
                                            <div class="r-phone-number input-style-1">
                                            <input type="tel" name="phone"  style="margin: 0px; border-width: 0px; width: 323px; text-align: right; position: relative; right: auto; left: 15px;" class="input-style-1">
                                            <i class="fas fa-info-circle"></i>
                                            </div>
                                                @if($errors->any())
                                                    <div class="alert alert-danger">
                                                        <ul>
                                                            @foreach($errors as $error)
                                                                {{$error}}
                                                            @endforeach
                                                        </ul>
                                                    </div>
                                                @endif
                                                <slot name="footer">
                                                    <div class="modal-footer">
                                                      <button type="submit" class="btn btn-primary center-block wid-100">register</button>
                                                    </div>
                                                </slot>
                                            </form>
                                                </slot>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </transition>
                </script>
                <a id="show-modal" @click="showRegister = true" class="l-main">register</a>
                <modal v-if="showRegister" @close="showRegister = false">
                </modal>
</code>```

答:
When you redirect back, pass an extra paramenter in view like: view('yourRoute', ['registerError'=>true]).
In your vue component receive it like <lr-pc register-error="{{$registerError}}"></lr-pc>. So you could handle it inside vue element.

```<code>new Vue({
        el: '.LR-PC',
        props:{
           registerError:{
               type:Boolean,
               default: false
           }
        },
        data: {
            showRegister: this.registerError,
            showLogin:false,
        }
    });
</code>```

Of course, if you wish an inverse logic, use !this.registerError.

Title: Make modal open after request - Vue.js

Body:
i have a register modal with vuejs and i need if user inserted the wrong information in the form and the information didn't validated in controller (using laravel) i could redirect user to the same page with modal open (i have "showRegister" in data and i need to make it open with "showRegister : true" after redirect)

    new Vue({
        el: '.LR-PC',
        data: {
            showRegister: false,
            showLogin:false,
        }
    });

on default when we redirect to page showRegister is false

code:

                register
                <modal v-if="showRegister" @close="showRegister = false">
                </modal>

Body:
When you redirect back, pass an extra paramenter in view like: view('yourRoute', ['registerError'=>true]).
In your vue component receive it like <lr-pc register-error="{{$registerError}}"></lr-pc>. So you could handle it inside vue element.

new Vue({
        el: '.LR-PC',
        props:{
           registerError:{
               type:Boolean,
               default: false
           }
        },
        data: {
            showRegister: this.registerError,
            showLogin:false,
        }
    });

Of course, if you wish an inverse logic, use !this.registerError.


问:
Getters and setters in parent class
I have a quick question on best practice and if getters and setters are the best option in a specific case.  The case is when I have class 'A' instantiating classes 'B' and 'C'.  Class A contains public getters and setters for classes B and C to access so data is centralised.

Is this best practice or would it be best to pass the data to classes B and C through parameters?

Thanks

Chris

答: Yes. This way the scope of B and C classes is reduced and can be accessible through A only.</p>

Title: Getters and setters in parent class


问:
Python BreathFirstSearch -pathing problem
This is my first post here, I am a python beginner working on a project for school.

My specific problem is a part of the berkeley pacman project1: https://inst.eecs.berkeley.edu/~cs188/sp19/project1.html

On the BFS part I am running into trouble. specifically on the tinyMap while my program is in 2,2 state it transitions to 2,3 normally but 2,1 has an extra north direction.

successorsVisited is a set of coordinate states
myQueue is a regular queue
problem is the board
getSuccessors returns a list of Tuples (state, direction, cost) which i edit into (state, direction, cost, path) before pushing it back into the queue.

please assume I have handled the base case correctly this is the iteration step starting with 5,4 and 4,5 in the queue.

```<code>def BFS_Helper(problem,myQueue,successorsVisited):
    while not myQueue.isEmpty():
        node = myQueue.pop()
        state = node[0]
        for x in range(0,len(problem.getSuccessors(state))):
            aTuple = problem.getSuccessors(state)[x]
            if aTuple[0] not in successorsVisited:
                successorsVisited.add(aTuple[0])
                node[3].append(aTuple[1])
                bTuple = (aTuple[0], aTuple[1], aTuple[2],  node[3]) # new bTuple with path = path + action
                print(bTuple)
                if problem.isGoalState(aTuple[0]):
                    return bTuple[3]
                myQueue.push(bTuple)
    return BFS_Helper(problem, myQueue,successorsVisited)
</code>```

i print out a bTuple before checking the goal state here is the print out. the north that is bolded is my problem, i cannot figure out how it happened.

((5, 3), 'South', 1, ['South', 'South'])

((3, 5), 'West', 1, ['West', 'West'])

((4, 3), 'West', 1, ['South', 'South', 'West'])

((2, 5), 'West', 1, ['West', 'West', 'West'])

((4, 2), 'South', 1, ['South', 'South', 'West', 'South'])

((1, 5), 'West', 1, ['West', 'West', 'West', 'West'])

((3, 2), 'West', 1, ['South', 'South', 'West', 'South', 'West'])

((1, 4), 'South', 1, ['West', 'West', 'West', 'West', 'South'])

((2, 2), 'West', 1, ['South', 'South', 'West', 'South', 'West', 'West'])

((1, 3), 'South', 1, ['West', 'West', 'West', 'West', 'South', 'South'])

((2, 3), 'North', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North'])

((2, 1), 'South', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North', 'South'])

((1, 1), 'West', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North', 'South', 'West'])

Thank you very much for any assistance.

答:
The cause of your problem is here:

```<code>node[3].append(aTuple[1])
</code>```

This will become an issue when the loop over the successors has more iterations. In those iterations the same node[3] is used... which still has the appended value in it from a previous iteration, and you add yet another value to it.

Solution: don't mutate node[3]. Instead, create a new list on-the-fly:

```<code>bTuple = (aTuple[0], aTuple[1], aTuple[2],  node[3] + [aTuple[1]])
</code>```

Body:
This is my first post here, I am a python beginner working on a project for school.

My specific problem is a part of the berkeley pacman project1: https://inst.eecs.berkeley.edu/~cs188/sp19/project1.html

On the BFS part I am running into trouble. specifically on the tinyMap while my program is in 2,2 state it transitions to 2,3 normally but 2,1 has an extra north direction.

successorsVisited is a set of coordinate states
myQueue is a regular queue
problem is the board
getSuccessors returns a list of Tuples (state, direction, cost) which i edit into (state, direction, cost, path) before pushing it back into the queue.

please assume I have handled the base case correctly this is the iteration step starting with 5,4 and 4,5 in the queue.

def BFS_Helper(problem,myQueue,successorsVisited):
    while not myQueue.isEmpty():
        node = myQueue.pop()
        state = node[0]
        for x in range(0,len(problem.getSuccessors(state))):
            aTuple = problem.getSuccessors(state)[x]
            if aTuple[0] not in successorsVisited:
                successorsVisited.add(aTuple[0])
                node[3].append(aTuple[1])
                bTuple = (aTuple[0], aTuple[1], aTuple[2],  node[3]) # new bTuple with path = path + action
                print(bTuple)
                if problem.isGoalState(aTuple[0]):
                    return bTuple[3]
                myQueue.push(bTuple)
    return BFS_Helper(problem, myQueue,successorsVisited)

i print out a bTuple before checking the goal state here is the print out. the north that is bolded is my problem, i cannot figure out how it happened.

((5, 3), 'South', 1, ['South', 'South'])

((3, 5), 'West', 1, ['West', 'West'])

((4, 3), 'West', 1, ['South', 'South', 'West'])

((2, 5), 'West', 1, ['West', 'West', 'West'])

((4, 2), 'South', 1, ['South', 'South', 'West', 'South'])

((1, 5), 'West', 1, ['West', 'West', 'West', 'West'])

((3, 2), 'West', 1, ['South', 'South', 'West', 'South', 'West'])

((1, 4), 'South', 1, ['West', 'West', 'West', 'West', 'South'])

((2, 2), 'West', 1, ['South', 'South', 'West', 'South', 'West', 'West'])

((1, 3), 'South', 1, ['West', 'West', 'West', 'West', 'South', 'South'])

((2, 3), 'North', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North'])

((2, 1), 'South', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North', 'South'])

((1, 1), 'West', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North', 'South', 'West'])

Thank you very much for any assistance.

Body:
The cause of your problem is here:

node[3].append(aTuple[1])

This will become an issue when the loop over the successors has more iterations. In those iterations the same node[3] is used... which still has the appended value in it from a previous iteration, and you add yet another value to it.

Solution: don't mutate node[3]. Instead, create a new list on-the-fly:

bTuple = (aTuple[0], aTuple[1], aTuple[2],  node[3] + [aTuple[1]])


问:
how can I check if a queue exists on Activemq
I have this method that throws me an exception when the data queue doesn't exists, but is not. Do you have other way to solve this?</p>

```<code>public void checkDataQueue(String dataQueue) throws JMSException {

          Connection connection = null;
          Session session = null;
          connection = jmsTemplate.getConnectionFactory().createConnection();
          session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

          Queue queue = session.createQueue(dataQueue);
          QueueBrowser browser = session.createBrowser(queue);
      }
</code>```

答:
thank you Tim, I solved it with these method. </p>

```<code>public boolean existDataQueue(String dataQueue) throws JMSException {
            boolean response = false;
            ActiveMQConnectionFactory activeMQConnectionFactory =
                new ActiveMQConnectionFactory();
            activeMQConnectionFactory.setBrokerURL(brokerUrl);
            ActiveMQConnection connection = (ActiveMQConnection)activeMQConnectionFactory.createConnection();

            connection.start();

            DestinationSource ds = connection.getDestinationSource();

            Set<ActiveMQQueue> queues = ds.getQueues();

            for (ActiveMQQueue activeMQQueue : queues) {
                try {
                    if(activeMQQueue.getQueueName().equalsIgnoreCase(dataQueue)) {
                        response = true;
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            connection.close();
            return response;
      }
</code>```

Body:
I have this method that throws me an exception when the data queue doesn't exists, but is not. Do you have other way to solve this?

public void checkDataQueue(String dataQueue) throws JMSException {

          Connection connection = null;
          Session session = null;
          connection = jmsTemplate.getConnectionFactory().createConnection();
          session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

          Queue queue = session.createQueue(dataQueue);
          QueueBrowser browser = session.createBrowser(queue);
      }

Body:
thank you Tim, I solved it with these method.

public boolean existDataQueue(String dataQueue) throws JMSException {
            boolean response = false;
            ActiveMQConnectionFactory activeMQConnectionFactory =
                new ActiveMQConnectionFactory();
            activeMQConnectionFactory.setBrokerURL(brokerUrl);
            ActiveMQConnection connection = (ActiveMQConnection)activeMQConnectionFactory.createConnection();

            connection.start();

            DestinationSource ds = connection.getDestinationSource();

            Set<ActiveMQQueue> queues = ds.getQueues();

            for (ActiveMQQueue activeMQQueue : queues) {
                try {
                    if(activeMQQueue.getQueueName().equalsIgnoreCase(dataQueue)) {
                        response = true;
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            connection.close();
            return response;
      }


问:
No Buildpack found while deploying to Heroku

This is my file tree containing a folder for my Vue app (client folder) and my NodeJS server (server folder).

When I try uploading to Heroku, I get an error saying that no matching buildpacks could be found, and that's I believe due to my source folder not having a package.js and that being because I have one in the client and server folders.

So how can I accomplish deploying both my client and server-side in one Heroku app, or would I need to split my whole app in one Heroku Front-End App and one Heroku Back-End App?

I'm sorry for such a stupid question, but I am really confused on how to put my app live, since it's finally finished after a month of work.

答:
No Buildpack found while deploying to Heroku .. When I try uploading to Heroku, I get an error saying that no matching buildpacks could be found, and that's I believe due to my source folder not having a package.js

Correct, this error "no buildpack found" happens because Heroku looks at (only) your root directory and cannot determine what language/framework you are using.

The package.json file defines the dependencies that should be installed with your application. To create a package.json file for your app, run the command npm init in the root directory of your app.
  https://devcenter.heroku.com/articles/deploying-nodejs#declare-app-dependencies

I'd recommend reading the heroku node docs and deploying a "hello world" application first, as a learning experience. You'll also want to read about the Procfile.

Deploying a client-server application to Heroku is quite common, all rails apps work this way (a single deploy). But, for node apps, there are many different ways to deploy, and there is no official (documented) way to organize your code, AFAIK.


问:
Getting the aspect ratio of any video
I want to get the aspect ratio of nay video in android like (1:1, 9:16 etc). Currently i get the height and width of a video but i want the aspect ratio. Is this task is possible with Ffmpeg or MediaMetadataRetriever? If yes, then please give me some example code. If no, then please suggest me the other solutions.</p>

答:
ffprobe

$ ffprobe -loglevel error -show_entries stream=sample_aspect_ratio,display_aspect_ratio -of default=nw=1 input.mkv
  sample_aspect_ratio=115:87
  display_aspect_ratio=1840:783
```

<p>This will provide both the SAR and DAR.</p>

<h1>mediainfo</h1>

<pre class="lang-none prettyprint-override"><code>$ mediainfo --Output="Video;%DisplayAspectRatio%,%DisplayAspectRatio/String%,%PixelAspectRatio%,%DisplayAspectRatio_Original%,%DisplayAspectRatio_Original/String%" input.mkv
  2.350,2.35:1,1.322,1.778,16:9
</code>```

As shown in this example there are many aspect ratios to choose from and they can be displayed in several forms, such as 16:9 or 1.778.

For more info see mediainfo --Help-Output and mediainfo --Info-Parameters.

Title: Getting the aspect ratio of any video

Body:
ffprobe

$ ffprobe -loglevel error -show_entries stream=sample_aspect_ratio,display_aspect_ratio -of default=nw=1 input.mkv
  sample_aspect_ratio=115:87
  display_aspect_ratio=1840:783

This will provide both the SAR and DAR.

mediainfo

$ mediainfo --Output="Video;%DisplayAspectRatio%,%DisplayAspectRatio/String%,%PixelAspectRatio%,%DisplayAspectRatio_Original%,%DisplayAspectRatio_Original/String%" input.mkv
  2.350,2.35:1,1.322,1.778,16:9

As shown in this example there are many aspect ratios to choose from and they can be displayed in several forms, such as 16:9 or 1.778.

For more info see mediainfo --Help-Output and mediainfo --Info-Parameters.


问:
How to concatenate two arrays using PHP?
I have two arrays:

```<code>$browser = array("firefox", "opera", "edge");
$version = array("10", "12", "14");
</code>```

I want to concatenate them such a way that the final array should be:

```<code>array(0=>array("name"=>"firefox", "version"=>"10"), 1=>array("name"=>"opera", "version"=>"12"), 2=>array("name"=>"edge", "version"=>"14"));
</code>```

The code can contain any builtin or user defined function. I have tried using:

```<code>$browser = array("firefox","opera","edge");
$version = array("10","12","14");
foreach($browser as $key=>$values){
  if(!isset($array)){
    $array = array("name"=>$browser[$key],"version"=>$version[$key]);
  }else{
    $array = array($array,array("name"=>$browser[$key],"version"=>$version[$key]));
  }
}
print_r($array);
</code>```

And the output I got was:

```<code>Array ( [0] => Array ( [0] => Array ( [name] => firefox [version] => 10 ) [1] => Array ( [name] => opera [version] => 12 ) ) [1] => Array ( [name] => edge [version] => 14 ) )
</code>```

Also note that this code is in PHP and should work for at least 10 arrays length data.

答:
I would just map the arrays:

```<code>$result = array_map(function($b, $v) {
                        return ['browser' => $b, 'version' => $v];
                    }, $browser, $version);
</code>```

You can also use an array for dynamic keys:

```<code>$keys = ['browser', 'version'];
$result = array_map(function($b, $v) use($keys) {
                        return array_combine($keys, [$b, $v]);
                    }, $browser, $version);
</code>```

However with your code just use the first format in the if and dynamically append []:

```<code>foreach($browser as $key=>$values){
    $array[] = array("name"=>$browser[$key],"version"=>$version[$key]);
}
</code>```

Body:
I have two arrays:

$browser = array("firefox", "opera", "edge");
$version = array("10", "12", "14");

I want to concatenate them such a way that the final array should be:

array(0=>array("name"=>"firefox", "version"=>"10"), 1=>array("name"=>"opera", "version"=>"12"), 2=>array("name"=>"edge", "version"=>"14"));

The code can contain any builtin or user defined function. I have tried using:

$browser = array("firefox","opera","edge");
$version = array("10","12","14");
foreach($browser as $key=>$values){
  if(!isset($array)){
    $array = array("name"=>$browser[$key],"version"=>$version[$key]);
  }else{
    $array = array($array,array("name"=>$browser[$key],"version"=>$version[$key]));
  }
}
print_r($array);

And the output I got was:

Array ( [0] => Array ( [0] => Array ( [name] => firefox [version] => 10 ) [1] => Array ( [name] => opera [version] => 12 ) ) [1] => Array ( [name] => edge [version] => 14 ) )

Also note that this code is in PHP and should work for at least 10 arrays length data.

Body:
I would just map the arrays:

$result = array_map(function($b, $v) {
                        return ['browser' => $b, 'version' => $v];
                    }, $browser, $version);

You can also use an array for dynamic keys:

$keys = ['browser', 'version'];
$result = array_map(function($b, $v) use($keys) {
                        return array_combine($keys, [$b, $v]);
                    }, $browser, $version);

However with your code just use the first format in the if and dynamically append []:

foreach($browser as $key=>$values){
    $array[] = array("name"=>$browser[$key],"version"=>$version[$key]);
}


问:
Is there a way to print a pointer with %x argument
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

```
gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls
```

this  is the  code

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

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}
</code>```

答:
To print the value that the pointer points to, you have to dereference it with *.

```<code>printf("The value of ptr is: %d\n", *ptr);
</code>```

But this will cause undefined behavior if ptr is NULL, you have to assign it to point to a valid int.

```<code>int a = 123;
int *ptr = &a;
</code>```

Then it will print 123.

Body:
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls

this  is the  code

#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}

Body:
To print the value that the pointer points to, you have to dereference it with *.

printf("The value of ptr is: %d\n", *ptr);

But this will cause undefined behavior if ptr is NULL, you have to assign it to point to a valid int.

int a = 123;
int *ptr = &a;

Then it will print 123.


问:
Apply function to tuple of vectors to get tuple of elements (variadic templates)
I have a container class which takes a list of vector or array objects (and stores a tuple of references to the original list of objects). Now, when calling the container via operator()(size_t idx) I want the function to return a tuple that contains the elements at index idx of each of the vectors/arrays.

    template<class... Ts>
    class Container
    {
    public:
        Container(const Ts&... objs)
            : m_data(objs...) { }

        auto operator()(size_t idx) const
        {
            const auto get_idx = [idx](const auto& obj) { return obj.at(idx);  };
            return std::tuple<const Ts::value_type& ...>((get_idx(m_data), ...));  // <-- does not compile
        }

    private:
        std::tuple<const Ts&...> m_data;
    };

    int main()
    {
        std::vector<int> v1{ 3,4,12,5 };
        std::vector<std::string> v2{ "on", "test", "ABC", "house" };
        std::array<double, 4> v3 = { 3.14, 2.71, 99.3, 128 };

        const auto z = Container(v1, v2, v3);

        auto v = z(2);  // <-- does not compile
        return 0;
    }
```

For example, z(2) above should be equal to std::tuple<int, std::string, double>(12, "ABC", 99.3). How would I achieve that?

答:
You have a tuple and you need to turn it into a pack. The way to do that is with std::apply():

```<code>auto operator()(size_t idx) const
{
    return std::apply([=](auto const&... xs){
        return std::make_tuple(xs.at(idx)...);
    }, m_data);
}
</code>```

xs here is a pack that refers to the contents of m_data. Once we have the pack, doing anything with it is straightforward.

Body:
I have a container class which takes a list of vector or array objects (and stores a tuple of references to the original list of objects). Now, when calling the container via operator()(size_t idx) I want the function to return a tuple that contains the elements at index idx of each of the vectors/arrays.

    template<class... Ts>
    class Container
    {
    public:
        Container(const Ts&... objs)
            : m_data(objs...) { }

        auto operator()(size_t idx) const
        {
            const auto get_idx = [idx](const auto& obj) { return obj.at(idx);  };
            return std::tuple<const Ts::value_type& ...>((get_idx(m_data), ...));  // <-- does not compile
        }

    private:
        std::tuple<const Ts&...> m_data;
    };

    int main()
    {
        std::vector<int> v1{ 3,4,12,5 };
        std::vector<std::string> v2{ "on", "test", "ABC", "house" };
        std::array<double, 4> v3 = { 3.14, 2.71, 99.3, 128 };

        const auto z = Container(v1, v2, v3);

        auto v = z(2);  // <-- does not compile
        return 0;
    }

For example, z(2) above should be equal to std::tuple<int, std::string, double>(12, "ABC", 99.3). How would I achieve that?

Body:
You have a tuple and you need to turn it into a pack. The way to do that is with std::apply():

auto operator()(size_t idx) const
{
    return std::apply([=](auto const&... xs){
        return std::make_tuple(xs.at(idx)...);
    }, m_data);
}

xs here is a pack that refers to the contents of m_data. Once we have the pack, doing anything with it is straightforward.