问:
How to get the Enum Index value in C#
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.

How to achieve the same with C#?

答:
```<code>using System;
public class EnumTest
{
    enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

    static void Main()
    {

        int x = (int)Days.Sun;
        int y = (int)Days.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}
</code>```

Title: How to get the Enum Index value in C#


来源: stackexchange

问:
Creating an array of IDs and randomize their age
I have to generate 160k of IDs in a text file and have to randomize their age.
I have generated the IDs using an array but I don't know how to randomize their age into the text file.

There is also a criteria to randomize the age :

10% from 160000 IDs are 60-90 years old,

30% for 25-60

25% for 13-24

35% for 1-12

here are the code for my random ID generate :

```<code>public class Citizenid {
    public static void main(String[] args) {

         try{
             try (PrintWriter p = new PrintWriter("citizen id.txt")) {

                    int totalAgesToGenerate = 160000;
                    int ages60To90 = (int) (totalAgesToGenerate * 0.1);
                    int ages25To59 = (int) (totalAgesToGenerate * 0.3);
                    int ages13To24 = (int) (totalAgesToGenerate * 0.25);
                    int ages1To12 = (int) (totalAgesToGenerate * 0.35);

                    Random r = new Random();
                    int age;
                    int index=0;
                    int []agearray;
                    agearray = new int[160000];

                    //generating age for 60-90 age group
                    for (int i = 0; i < ages60To90; i++) {
                        age = r.nextInt(31) + 60;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 25-59 age group
                    for (int i = 0; i < ages25To59; i++) {
                        age = r.nextInt(35) + 25;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 13-24 age group
                    for (int i = 0; i < ages13To24; i++) {
                        age = r.nextInt(12) + 13;
                        agearray[index]=age;
                        index++;
                    }
                     //generating age for 1-12 age group
                    for (int i = 0; i < ages1To12; i++) {
                        age = r.nextInt(12) + 1;
                        agearray[index]=age;
                        index++;
                    }

                 int a=1;
                 int[]arrayid = new int[160000];
                 for(int i=0;i<arrayid.length;i++){
                     p.printf("%06d , %d \n",a,agearray[r.nextInt(1600001)]);
                     a++;
                 }
                 p.close();
             }
            }
        catch(Exception e)
        {

             System.out.println("No such file exist");
        }
    }
}
</code>```

I have solved the age problem but I wonder why the output is "No such file exist". It doesn't write on the textile

答:
```<code>for(int i=0;i<arrayid.length;i++){
    p.printf("%06d %2d\n",a, getRandomAge());
    a++;
}
// ------ outside main function ------
private static Random random = new Random();

private static int getRandomAge() {
    int groupId = random.nextInt(100);
    if (groupId < 10) {
        return 60 + random.nextInt(30); // 10% age 60-90
    } else if (groupId < 40) {
        return 25 + random.nextInt(35); // 30% age 25-60
    } else if (groupId < 65) {
        return 13 + random.nextInt(11); // 25% age 13-24
    }
    return 1 + random.nextInt(12); // the rest 35% age 1-13
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to generate 160k of IDs in a text file and have to randomize their age.
I have generated the IDs using an array but I don't know how to randomize their age into the text file.

There is also a criteria to randomize the age :

10% from 160000 IDs are 60-90 years old,

30% for 25-60

25% for 13-24

35% for 1-12

here are the code for my random ID generate :

public class Citizenid {
    public static void main(String[] args) {

         try{
             try (PrintWriter p = new PrintWriter("citizen id.txt")) {

                    int totalAgesToGenerate = 160000;
                    int ages60To90 = (int) (totalAgesToGenerate * 0.1);
                    int ages25To59 = (int) (totalAgesToGenerate * 0.3);
                    int ages13To24 = (int) (totalAgesToGenerate * 0.25);
                    int ages1To12 = (int) (totalAgesToGenerate * 0.35);

                    Random r = new Random();
                    int age;
                    int index=0;
                    int []agearray;
                    agearray = new int[160000];

                    //generating age for 60-90 age group
                    for (int i = 0; i < ages60To90; i++) {
                        age = r.nextInt(31) + 60;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 25-59 age group
                    for (int i = 0; i < ages25To59; i++) {
                        age = r.nextInt(35) + 25;
                        agearray[index]=age;
                        index++;
                    }
                    //generating age for 13-24 age group
                    for (int i = 0; i < ages13To24; i++) {
                        age = r.nextInt(12) + 13;
                        agearray[index]=age;
                        index++;
                    }
                     //generating age for 1-12 age group
                    for (int i = 0; i < ages1To12; i++) {
                        age = r.nextInt(12) + 1;
                        agearray[index]=age;
                        index++;
                    }

                 int a=1;
                 int[]arrayid = new int[160000];
                 for(int i=0;i<arrayid.length;i++){
                     p.printf("%06d , %d \n",a,agearray[r.nextInt(1600001)]);
                     a++;
                 }
                 p.close();
             }
            }
        catch(Exception e)
        {

             System.out.println("No such file exist");
        }
    }
}

I have solved the age problem but I wonder why the output is "No such file exist". It doesn't write on the textile


问:
Field Calculator & Python 3 String Reclass Warning
I am throwing a python 3 warning in ArcPro which states:

Warning 002858: Certain rows set to NULL due to error while evaluating python expression: File "string", line 3, in reclass

The code I am using is as follows:

UpOrDown_PerAcre = reclass(!GP2040Area!,!UpOrDownNum!)

Code Block

def reclass(GP2040AREA, UpOrDownNum):
    if (UpOrDownNum != 0 or UpOrDownNum != 999):
        UpOrDown_PerAcre = GP2040AREA * UpOrDownNum
        return UpOrDown_PerAcre

What I am trying to do is, for every cell in UpOrDownNum that is not 0 or 999, output the multiple of cell GP2040ArEA and UpOrDownNum in the new column UpOrDown_PerAcre.

Line 3 would, from my understanding, be "UpOrDown_PerAcre = GP2040AREA * UpOrDownNum" which is saying the output is a string? I did have the if statement classified as if (UpOrDownNum == int and UpOrDownNum != 0 or UpOrDownNum != 999): because there -are- null values in UpOrDownNum which may be throwing a 'string' warning but it was the same after removing that from the if statement.

Where exactly did I go wrong?

答:
Perhaps check UpOrDownNum is not None (Python's version of null):</p>

```<code>def reclass(GP2040AREA, UpOrDownNum):
    if (UpOrDownNum is not None and (UpOrDownNum != 0 or UpOrDownNum != 999)):
        UpOrDown_PerAcre = GP2040AREA * UpOrDownNum
        return UpOrDown_PerAcre
    else:
        return None # or 0 or -1 or whatever you want to signify the UpOrDown_PerAcre wasn't calculated
</code>```

Body:
Perhaps check UpOrDownNum is not None (Python's version of null):

def reclass(GP2040AREA, UpOrDownNum):
    if (UpOrDownNum is not None and (UpOrDownNum != 0 or UpOrDownNum != 999)):
        UpOrDown_PerAcre = GP2040AREA * UpOrDownNum
        return UpOrDown_PerAcre
    else:
        return None # or 0 or -1 or whatever you want to signify the UpOrDown_PerAcre wasn't calculated


问:
Python rotating the elements inside subarrays
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

```<code>def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
</code>```

Imagine a is 10 and b is 1 the output is:

```<code>[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
</code>```

But how can i reverse each subarrays b times?

The output that i want;

```<code>[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]
</code>```

Body:
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]

Imagine a is 10 and b is 1 the output is:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

But how can i reverse each subarrays b times?

The output that i want;

[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]

Body:
You can rotate the inner lists by slicing:

def reorder(a,b):
    slicingPosition = a/2 % b
    return [y[-slicingPosition:] + y[:-slicingPosition] for y in [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]]

for x in range(1, 6):
    print(x, '>>', reorder(10, x))

Output:

(1, '>>', [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
(2, '>>', [[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])
(3, '>>', [[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]])
(4, '>>', [[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])
(5, '>>', [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])


问:
How to create a interface "X" extending List interface and implement X using a abstract class Y with ArrayList
Currently am stuck in a peculiar state. I would like to create an interface X which extends java.util.List interface.

Meantime, I am creating an Abstract class Y which implements "X" partially. However, I don't wish to implement methods of List. Is possible to wire them together using ArrayList?

```<code>public interface X extends Serializable, Cloneable, List<MessageObject>, RandomAccess {

}

public abstract class Y implements X {
}
</code>```

Regarding the above code, Y needs to implement all methods of ArrayList. Is it possible to workaround this? Even creating one more layer inbetween the class should be fine.

The requirement is "Y" should have all methods and functionality of ArrayList.

答:
You should be able to inherit them from ArrayList.</p>

```<code>public abstract class Y extends ArrayList<MessageObject> implements X {
}
</code>```

Body:
Currently am stuck in a peculiar state. I would like to create an interface X which extends java.util.List interface.

Meantime, I am creating an Abstract class Y which implements "X" partially. However, I don't wish to implement methods of List. Is possible to wire them together using ArrayList?

public interface X extends Serializable, Cloneable, List<MessageObject>, RandomAccess {

}

public abstract class Y implements X {
}

Regarding the above code, Y needs to implement all methods of ArrayList. Is it possible to workaround this? Even creating one more layer inbetween the class should be fine.

The requirement is "Y" should have all methods and functionality of ArrayList.

Body:
You should be able to inherit them from ArrayList.

public abstract class Y extends ArrayList<MessageObject> implements X {
}


问:
WifiNetworkSpecifier bypass user selection
I'm trying to implement a WiFi peer to peer network as described in the documentation:

https://developer.android.com/guide/topics/connectivity/wifi-bootstrap

I'm doing this to make the app future proof, older version of app simply added a Wifinetwork without any big deal but that is being deprecated now so I'm trying to use the new method for devices running Android 10.

Here is my code (called from a foreground service):

```<code> if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();

            builder.setBssid(MacAddress.fromString("00:08:22:C0:9F:4A"));
            builder.setWpa2Passphrase("password");

            WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
            NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
            networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
            networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);

            NetworkRequest networkRequest = networkRequestBuilder.build();
            final ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(@NonNull Network network) {
                        //Use this network object to Send request.
                        //eg - Using OkHttp library to create a service request
                        InetAddress server = cm.getLinkProperties(network).getDnsServers().get(0);
                        Log.d(TAG,"Got the following address: "+server.getHostAddress());

                        super.onAvailable(network);
                    }
                });

            }
        }
</code>```

This indeed works as expected, it does show the user a dialog with the available network and the user can select it, then I get a callback, and access the network as I need to.
As soon as my foreground service stops, the WiFi connection is being teared off which is exactly what it's needed.

However next time when I try to connect, I get the same window asking the user to select the network, but based on the documentation from here: https://developer.android.com/guide/topics/connectivity/wifi-bootstrap#bypass-approval as long as I haven't forget the network while I was connected to it and did not used pattern for BSSID or SSID, this should be remembered and user approval should be bypassed.
What am I'm missing, why do I keep getting the user approval window?

I thought it might be something limited to Activity/Service, but I experience the same behaviour even if I call this from an Activity.

答:
Found the problem,issue. Might be my English or might be the documentation which wasn't obvious.

If the app makes a non-specific request, such as with an SSID or BSSID pattern, then the user must approve the request.

This means that both SSID and BSSID must be set. Not setting a BSSID is equivalent of setting a BSSID pattern. I realised this when I logged the NetworkRequest builder.
In order to have the app automatically connect again to the network, you need to set up both values SSID and BSSID as well.

Body:
I'm trying to implement a WiFi peer to peer network as described in the documentation:

https://developer.android.com/guide/topics/connectivity/wifi-bootstrap

I'm doing this to make the app future proof, older version of app simply added a Wifinetwork without any big deal but that is being deprecated now so I'm trying to use the new method for devices running Android 10.

Here is my code (called from a foreground service):

 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();

            builder.setBssid(MacAddress.fromString("00:08:22:C0:9F:4A"));
            builder.setWpa2Passphrase("password");

            WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
            NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
            networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
            networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);

            NetworkRequest networkRequest = networkRequestBuilder.build();
            final ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(@NonNull Network network) {
                        //Use this network object to Send request.
                        //eg - Using OkHttp library to create a service request
                        InetAddress server = cm.getLinkProperties(network).getDnsServers().get(0);
                        Log.d(TAG,"Got the following address: "+server.getHostAddress());

                        super.onAvailable(network);
                    }
                });

            }
        }

This indeed works as expected, it does show the user a dialog with the available network and the user can select it, then I get a callback, and access the network as I need to.
As soon as my foreground service stops, the WiFi connection is being teared off which is exactly what it's needed.

However next time when I try to connect, I get the same window asking the user to select the network, but based on the documentation from here: https://developer.android.com/guide/topics/connectivity/wifi-bootstrap#bypass-approval as long as I haven't forget the network while I was connected to it and did not used pattern for BSSID or SSID, this should be remembered and user approval should be bypassed.
What am I'm missing, why do I keep getting the user approval window?

I thought it might be something limited to Activity/Service, but I experience the same behaviour even if I call this from an Activity.


问:
How to remove categories with no products?
I am a bit stuck on the following SQL:

```<code>delete  from oc_category_description where 'category_id' NOT in (SELECT category_id FROM oc_product_to_category);
delete from oc_category_path where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_store where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_layout where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_filter where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_coupon_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
</code>```

It removes all data ignoring the where part. What am I doing wrong?

答:
You need to remove the single quotes around the column name, otherwise it becomes a literal string, and the expression does not do what you want. It actually checks if literal string 'category_id' belongs to the resulset of the subquery: since it probably does not, all rows get deleted.

Also, I would recommend using exists, which is null-safe, while not in is not (that is, if any value in the subquery is null, all rows will be deleted).

```<code>delete from oc_category
where not exists (
    select 1
    from oc_product_to_category pc
    where pc.category_id = oc_category.category_id
);
</code>```

For performance, consider an index on oc_product_to_category(category_id) (or at least a compound index where this column appears first).

Body:
I am a bit stuck on the following SQL:

delete  from oc_category_description where 'category_id' NOT in (SELECT category_id FROM oc_product_to_category);
delete from oc_category_path where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_store where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_to_layout where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category_filter where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_coupon_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);
delete from oc_category where 'category_id' NOT in(SELECT category_id from oc_product_to_category);

It removes all data ignoring the where part. What am I doing wrong?

Body:
You need to remove the single quotes around the column name, otherwise it becomes a literal string, and the expression does not do what you want. It actually checks if literal string 'category_id' belongs to the resulset of the subquery: since it probably does not, all rows get deleted.

Also, I would recommend using exists, which is null-safe, while not in is not (that is, if any value in the subquery is null, all rows will be deleted).

delete from oc_category
where not exists (
    select 1
    from oc_product_to_category pc
    where pc.category_id = oc_category.category_id
);

For performance, consider an index on oc_product_to_category(category_id) (or at least a compound index where this column appears first).


问:
Power Query - Change DateTime to Text without altering format
I'm trying to convert a DateTime field to Text in Power Query.

Currently the DateTime format is dd/mm//yyyy hh:mm:ss (e.g. 02/04/2006 00:00:00)

When I change the type in Power Query to Text, the output is formatted as mmmm d yyy hh:mm AM/PM (e.g. Apr 2 2006 12:00AM)

I want to retain the original format when I convert to text, how can I do this?

Thanks

答:
There isn't really an "original format" when it's stored as DateTime, it's just how your program chooses to represent it (which can vary regionally).

That said, you should be able to specify exactly the format you want. When you use the GUI to transform the data type it will produce a step that looks like this:

```<code>= Table.TransformColumnTypes(#"Previous Step",{{"Column1", type text}})
</code>```

Modify that a bit so it looks like this instead:

```<code>= Table.TransformColumns(#"Previous Step",
    {{"Column1", each DateTime.ToText(_, "MMM d yyyy hh:mm tt"), type text}})
</code>```

Body:
There isn't really an "original format" when it's stored as DateTime, it's just how your program chooses to represent it (which can vary regionally).

That said, you should be able to specify exactly the format you want. When you use the GUI to transform the data type it will produce a step that looks like this:

= Table.TransformColumnTypes(#"Previous Step",{{"Column1", type text}})

Modify that a bit so it looks like this instead:

= Table.TransformColumns(#"Previous Step",
    {{"Column1", each DateTime.ToText(_, "MMM d yyyy hh:mm tt"), type text}})


问:
Why is raising an NSException not bringing down my application?
The Problem

I'm writing a Cocoa application and I want to raise exceptions that will crash the application noisily.

I have the following lines in my application delegate:

```<code>[NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
abort();
</code>```

The problem is, they don't bring down the application - the message is just logged to the console and the app carries on it's merry way.

As I understand it, the whole point of exceptions is that they're fired under exceptional circumstances. In these circumstances, I want the application to quit in an obvious way. And this doesn't happen.

What I've tried

I've tried:

```<code>-(void)applicationDidFinishLaunching:(NSNotification *)note
    // ...
    [self performSelectorOnMainThread:@selector(crash) withObject:nil waitUntilDone:YES];
}

-(void)crash {
    [NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
    abort();
}
</code>```

which doesn't work and

```<code>-(void)applicationDidFinishLaunching:(NSNotification *)note
    // ...
    [self performSelectorInBackground:@selector(crash) withObject:nil];
}

-(void)crash {
    [NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
    abort();
}
</code>```

which, rather confusingly, works as expected.

What's going on? What am I doing wrong?

答:
I'm trying to understand this properly: Why does the following category method on NSApplication lead to an infinite loop? In that infinite loop, "An uncaught exception was raised" is logged out infinitely many times:

```<code>- (void)reportException:(NSException *)anException
{
    // handle the exception properly
    (*NSGetUncaughtExceptionHandler())(anException);
}
</code>```

For testing (and understanding purposes), this is the only thing I do, i.e. just create the above category method. (According to the instructions in http://www.cocoadev.com/index.pl?StackTraces)

Why would this cause an infinite loop? It's not consistent with what the default uncaught exception handler method should do, i.e. just log the exception and exit the program. (See http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Exceptions/Concepts/UncaughtExceptions.html#//apple_ref/doc/uid/20000056-BAJDDGGD)

Could it be that the default uncaught exception handler is actually throwing the exception again, leading to this infinite loop?

Note: I know it's silly to create only this category method. The purpose of this is to gain a better understanding.

UPDATE: Never mind, I think i get this now. Here is my take. By default, as we know, NSApplication's reportException: method logs the exception. But, according to the docs, the default uncaught exception handler logs the exception and exists the program. However, this should be worded like this in the docs to be more precise: The default uncaught exception handler calls NSApplication's reportException: method (in order to log it, which the method's default implementation indeed does), and then exists the program. So now it should be clear why calling the default uncaught exception handler inside an overridden reportException: causes an infinite loop: The former calls the latter.

ContentLicense: CC BY-SA 2.5

Body:
The Problem

I'm writing a Cocoa application and I want to raise exceptions that will crash the application noisily.

I have the following lines in my application delegate:

[NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
abort();

The problem is, they don't bring down the application - the message is just logged to the console and the app carries on it's merry way.

As I understand it, the whole point of exceptions is that they're fired under exceptional circumstances. In these circumstances, I want the application to quit in an obvious way. And this doesn't happen.

What I've tried

I've tried:

-(void)applicationDidFinishLaunching:(NSNotification *)note
    // ...
    [self performSelectorOnMainThread:@selector(crash) withObject:nil waitUntilDone:YES];
}

-(void)crash {
    [NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
    abort();
}

which doesn't work and

-(void)applicationDidFinishLaunching:(NSNotification *)note
    // ...
    [self performSelectorInBackground:@selector(crash) withObject:nil];
}

-(void)crash {
    [NSException raise:NSInternalInconsistencyException format:@"This should crash the application."];
    abort();
}

which, rather confusingly, works as expected.

What's going on? What am I doing wrong?

Body:
I'm trying to understand this properly: Why does the following category method on NSApplication lead to an infinite loop? In that infinite loop, "An uncaught exception was raised" is logged out infinitely many times:

- (void)reportException:(NSException *)anException
{
    // handle the exception properly
    (*NSGetUncaughtExceptionHandler())(anException);
}

For testing (and understanding purposes), this is the only thing I do, i.e. just create the above category method. (According to the instructions in http://www.cocoadev.com/index.pl?StackTraces)

Why would this cause an infinite loop? It's not consistent with what the default uncaught exception handler method should do, i.e. just log the exception and exit the program. (See http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Exceptions/Concepts/UncaughtExceptions.html#//apple_ref/doc/uid/20000056-BAJDDGGD)

Could it be that the default uncaught exception handler is actually throwing the exception again, leading to this infinite loop?

Note: I know it's silly to create only this category method. The purpose of this is to gain a better understanding.

UPDATE: Never mind, I think i get this now. Here is my take. By default, as we know, NSApplication's reportException: method logs the exception. But, according to the docs, the default uncaught exception handler logs the exception and exists the program. However, this should be worded like this in the docs to be more precise: The default uncaught exception handler calls NSApplication's reportException: method (in order to log it, which the method's default implementation indeed does), and then exists the program. So now it should be clear why calling the default uncaught exception handler inside an overridden reportException: causes an infinite loop: The former calls the latter.

ContentLicense: CC BY-SA 3.0


问:
std::map holding any value type
Code:

```<code>#include <iostream>
#include<map>
using namespace std;

class MyClass {

public:

    class MyFieldInterface
    {
      public:
        int m_Size;
        ~MyFieldInterface() = default;
    };

    template <typename T>
    class MyField : public MyFieldInterface {
      public:
           MyField(T val) {m_Value = val;}
           T m_Value;
    };

    template <typename T>
    MyField<T>* getType(int type, T val) {
       if (type == 0) return new MyField<int>(val);
       if (type == 1) return new MyField<double>(val);
       if (type == 2) return new MyField<char>(val);
    }

    map<string, MyFieldInterface* > fields;
};

int main()
{
    MyClass obj;

    obj.fields["a"] = obj.getType<int>(0, 1);
    obj.fields["b"] = obj.getType<double>(1, 1.1);
    obj.fields["c"] = obj.getType<char>(2, 'a');

    return 0;
}
</code>```

Question:

I want std::map to hold any value type, thus I created a template class with dynamic inheritance.
 I have defined template class inside MyClass for the reason I don't want its definition to be exposed to user. Using getType function I will create a new object with given type which will be stored into the map.

With the above approach I get the below errors, I'm not able to succeed with the above approach.

```<code>main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = int]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',45)">main.cpp:45:44</span>:   required from here
main.cpp:34:53: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 1) return new MyField<double>(val);
                                                     ^
main.cpp:35:51: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 2) return new MyField<char>(val);
                                                   ^
main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = double]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',46)">main.cpp:46:49</span>:   required from here
main.cpp:33:50: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 0) return new MyField<int>(val);
                                                  ^
main.cpp:35:51: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 2) return new MyField<char>(val);
                                                   ^
main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = char]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',47)">main.cpp:47:47</span>:   required from here
main.cpp:33:50: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 0) return new MyField<int>(val);
                                                  ^
main.cpp:34:53: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 1) return new MyField<double>(val);
                                                     ^
</code>```

答:
You can't use a run-time parameter to choose between multiple types. You need to decide what type is returned at compile time. But this is exactly what templates are for, so you could simply do:

```<code>template <typename T>
MyField<T>* getType(T val) {
   return new MyField<T>(val);
}
</code>```

and then use the function like this:

```<code>obj.fields["a"] = obj.getType(1);
obj.fields["b"] = obj.getType(1.1);
obj.fields["c"] = obj.getType('a');
</code>```

Note that you don't need to specify T at the call site, since that can be deduced from the function argument.

Of course, you will need to keep track of what type each key in the map refers to separately.

Here's a demo.

Also, the way this function is implemented, the name getType is confusing, since you are not actually returning a type here. Perhaps a better name would be getAnyPointer.

Title: std::map holding any value type

Body:
Code:

#include <iostream>
#include<map>
using namespace std;

class MyClass {

public:

    class MyFieldInterface
    {
      public:
        int m_Size;
        ~MyFieldInterface() = default;
    };

    template <typename T>
    class MyField : public MyFieldInterface {
      public:
           MyField(T val) {m_Value = val;}
           T m_Value;
    };

    template <typename T>
    MyField<T>* getType(int type, T val) {
       if (type == 0) return new MyField<int>(val);
       if (type == 1) return new MyField<double>(val);
       if (type == 2) return new MyField<char>(val);
    }

    map<string, MyFieldInterface* > fields;
};

int main()
{
    MyClass obj;

    obj.fields["a"] = obj.getType<int>(0, 1);
    obj.fields["b"] = obj.getType<double>(1, 1.1);
    obj.fields["c"] = obj.getType<char>(2, 'a');

    return 0;
}

Question:

I want std::map to hold any value type, thus I created a template class with dynamic inheritance.
 I have defined template class inside MyClass for the reason I don't want its definition to be exposed to user. Using getType function I will create a new object with given type which will be stored into the map.

With the above approach I get the below errors, I'm not able to succeed with the above approach.

main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = int]’:
main.cpp:45:44:   required from here
main.cpp:34:53: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 1) return new MyField<double>(val);
                                                     ^
main.cpp:35:51: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 2) return new MyField<char>(val);
                                                   ^
main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = double]’:
main.cpp:46:49:   required from here
main.cpp:33:50: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 0) return new MyField<int>(val);
                                                  ^
main.cpp:35:51: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 2) return new MyField<char>(val);
                                                   ^
main.cpp: In instantiation of ‘MyClass::MyField<T>* MyClass::getType(int, T) [with T = char]’:
main.cpp:47:47:   required from here
main.cpp:33:50: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 0) return new MyField<int>(val);
                                                  ^
main.cpp:34:53: error: cannot convert ‘MyClass::MyField*’ to ‘MyClass::MyField*’ in return
        if (type == 1) return new MyField<double>(val);
                                                     ^

Body:
You can't use a run-time parameter to choose between multiple types. You need to decide what type is returned at compile time. But this is exactly what templates are for, so you could simply do:

template <typename T>
MyField<T>* getType(T val) {
   return new MyField<T>(val);
}

and then use the function like this:

obj.fields["a"] = obj.getType(1);
obj.fields["b"] = obj.getType(1.1);
obj.fields["c"] = obj.getType('a');

Note that you don't need to specify T at the call site, since that can be deduced from the function argument.

Of course, you will need to keep track of what type each key in the map refers to separately.

Here's a demo.

Also, the way this function is implemented, the name getType is confusing, since you are not actually returning a type here. Perhaps a better name would be getAnyPointer.


问:
Pi Hole with web interface and wordpress on the same Raspberry Pi 4
in my raspberry run pi hole with web int, i want to install also a wordpress site with local ip but when i try to install the component apache cannot start the server at the end of installation. How can i do to create a pvt site in local area with pi hole in the same RPi?
Thank you.
ps below the error code if can be usefull :)</p>

```<code>pi@PotatoServer:~ $ sudo apt install apache2 -y
Lettura elenco dei pacchetti... Fatto
Generazione albero delle dipendenze
Lettura informazioni sullo stato... Fatto
I seguenti pacchetti sono stati installati automaticamente e non sono più richiesti:
  alsa-base gstreamer0.10-alsa gstreamer0.10-plugins-base liba52-0.7.4
  libaribb24-0 libbasicusageenvironment1 libcddb2 libdav1d3 libdvbpsi10
  libebml4v5 libgroupsock8 libgstreamer-plugins-base0.10-0 libgstreamer0.10-0
  libixml10 liblirc-client0 liblivemedia64 libllvm8 libmatroska6v5
  libmicrodns0 libmpeg2-4 libopenmpt-modplug1 libplacebo7 libprotobuf-lite17
  libproxy-tools libresid-builder0c2a libsidplay2 libspatialaudio0
  libspeexdsp1 libupnp13 libusageenvironment3 libvlc-bin libvlc5 libvlccore9
  libxcb-xv0 libxfce4util-bin libxfce4util-common libxfce4util7 libxfconf-0-2
  pimixer point-rpi vlc-bin vlc-data vlc-l10n vlc-plugin-notify vlc-plugin-qt
  vlc-plugin-samba vlc-plugin-skins2 vlc-plugin-video-output
  vlc-plugin-video-splitter vlc-plugin-visualization xfconf
Usare "sudo apt autoremove" per rimuoverli.
Pacchetti suggeriti:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom
I seguenti pacchetti NUOVI saranno installati:
  apache2
0 aggiornati, 1 installati, 0 da rimuovere e 0 non aggiornati.
È necessario scaricare 0 B/251 kB di archivi.
Dopo quest'operazione, verranno occupati 613 kB di spazio su disco.
Selezionato il pacchetto apache2 non precedentemente selezionato.
(Lettura del database... 159463 file e directory attualmente installati.)
Preparativi per estrarre .../apache2_2.4.38-3+deb10u3_armhf.deb...
Estrazione di apache2 (2.4.38-3+deb10u3)...
Configurazione di apache2 (2.4.38-3+deb10u3)...
Enabling module mpm_event.
Enabling module authz_core.
Enabling module authz_host.
Enabling module authn_core.
Enabling module auth_basic.
Enabling module access_compat.
Enabling module authn_file.
Enabling module authz_user.
Enabling module alias.
Enabling module dir.
Enabling module autoindex.
Enabling module env.
Enabling module mime.
Enabling module negotiation.
Enabling module setenvif.
Enabling module filter.
Enabling module deflate.
Enabling module status.
Enabling module reqtimeout.
Enabling conf charset.
Enabling conf localized-error-pages.
Enabling conf other-vhosts-access-log.
Enabling conf security.
Enabling conf serve-cgi-bin.
Enabling site 000-default.
Created symlink /etc/systemd/system/multi-user.target.wants/apache2.service → /lib/systemd/system/apache2.service.
Created symlink /etc/systemd/system/multi-user.target.wants/apache-htcacheclean.service → /lib/systemd/system/apache-htcacheclean.service.
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.
invoke-rc.d: initscript apache2, action "start" failed.
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset:enabled)
   Active: failed (Result: exit-code) since Mon 2020-03-09 02:08:51 CET; 22ms ago
     Docs: https://httpd.apache.org/docs/2.4/
  Process: 637 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

mar 09 02:08:51 PotatoServer apachectl[637]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
mar 09 02:08:51 PotatoServer apachectl[637]: no listening sockets available, shutting down
mar 09 02:08:51 PotatoServer apachectl[637]: AH00015: Unable to open logs
mar 09 02:08:51 PotatoServer apachectl[637]: Action 'start' failed.
mar 09 02:08:51 PotatoServer apachectl[637]: The Apache error log may have more             information.
mar 09 02:08:51 PotatoServer systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE
mar 09 02:08:51 PotatoServer systemd[1]: apache2.service: Failed with result 'exit-code'.
mar 09 02:08:51 PotatoServer systemd[1]: Failed to start The Apache HTTP Server.
Elaborazione dei trigger per man-db (2.8.5-2)...
Elaborazione dei trigger per systemd (241-7~deb10u3+rpi1)...
}```
</code>```

答:
Pihole uses Lighttpd as its webserver which defaults to listening to listing on port 80.  Apache also listens on port 80 which is why you are getting the following error.

mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in
  use: AH00072: make_sock: could not bind to address [::]:80 mar 09
  02:08:51 PotatoServer apachectl[637]: (98)Address already in use:
  AH00072: make_sock: could not bind to address 0.0.0.0:80 mar 09
  02:08:51 PotatoServer apachectl[637]: no listening sockets available,
  shutting down mar 09 02:08:51 PotatoServer apachectl[637]: AH00015:
  Unable to open logs mar 09 02:08:51 PotatoServer apachectl[637]:
  Action 'start' failed.

To resolve this you would need to change the port that either Apache or Lighttpd are listening on.  To change Apache's default port on raspbian:

```<code>nano /etc/apache2/ports.conf
</code>```

Change Listen 80 to something else like Listen 8080.  Then hit ctrl-x and y to close and save the file.  Now you also need to change the virtual host statement.  For the default installation you can do this by editing 000-default.conf.

```<code>nano /etc/apache2/sites-enabld/000-default.conf
</code>```

Change VirtualHost *:80 to VirtualHost *:8080.  Then close and save the file again.

Finally, start Apache.

```<code>sudo /etc/init.d/apache2 start
</code>```

Body:
in my raspberry run pi hole with web int, i want to install also a wordpress site with local ip but when i try to install the component apache cannot start the server at the end of installation. How can i do to create a pvt site in local area with pi hole in the same RPi?
Thank you.
ps below the error code if can be usefull :)

pi@PotatoServer:~ $ sudo apt install apache2 -y
Lettura elenco dei pacchetti... Fatto
Generazione albero delle dipendenze
Lettura informazioni sullo stato... Fatto
I seguenti pacchetti sono stati installati automaticamente e non sono più richiesti:
  alsa-base gstreamer0.10-alsa gstreamer0.10-plugins-base liba52-0.7.4
  libaribb24-0 libbasicusageenvironment1 libcddb2 libdav1d3 libdvbpsi10
  libebml4v5 libgroupsock8 libgstreamer-plugins-base0.10-0 libgstreamer0.10-0
  libixml10 liblirc-client0 liblivemedia64 libllvm8 libmatroska6v5
  libmicrodns0 libmpeg2-4 libopenmpt-modplug1 libplacebo7 libprotobuf-lite17
  libproxy-tools libresid-builder0c2a libsidplay2 libspatialaudio0
  libspeexdsp1 libupnp13 libusageenvironment3 libvlc-bin libvlc5 libvlccore9
  libxcb-xv0 libxfce4util-bin libxfce4util-common libxfce4util7 libxfconf-0-2
  pimixer point-rpi vlc-bin vlc-data vlc-l10n vlc-plugin-notify vlc-plugin-qt
  vlc-plugin-samba vlc-plugin-skins2 vlc-plugin-video-output
  vlc-plugin-video-splitter vlc-plugin-visualization xfconf
Usare "sudo apt autoremove" per rimuoverli.
Pacchetti suggeriti:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom
I seguenti pacchetti NUOVI saranno installati:
  apache2
0 aggiornati, 1 installati, 0 da rimuovere e 0 non aggiornati.
È necessario scaricare 0 B/251 kB di archivi.
Dopo quest'operazione, verranno occupati 613 kB di spazio su disco.
Selezionato il pacchetto apache2 non precedentemente selezionato.
(Lettura del database... 159463 file e directory attualmente installati.)
Preparativi per estrarre .../apache2_2.4.38-3+deb10u3_armhf.deb...
Estrazione di apache2 (2.4.38-3+deb10u3)...
Configurazione di apache2 (2.4.38-3+deb10u3)...
Enabling module mpm_event.
Enabling module authz_core.
Enabling module authz_host.
Enabling module authn_core.
Enabling module auth_basic.
Enabling module access_compat.
Enabling module authn_file.
Enabling module authz_user.
Enabling module alias.
Enabling module dir.
Enabling module autoindex.
Enabling module env.
Enabling module mime.
Enabling module negotiation.
Enabling module setenvif.
Enabling module filter.
Enabling module deflate.
Enabling module status.
Enabling module reqtimeout.
Enabling conf charset.
Enabling conf localized-error-pages.
Enabling conf other-vhosts-access-log.
Enabling conf security.
Enabling conf serve-cgi-bin.
Enabling site 000-default.
Created symlink /etc/systemd/system/multi-user.target.wants/apache2.service → /lib/systemd/system/apache2.service.
Created symlink /etc/systemd/system/multi-user.target.wants/apache-htcacheclean.service → /lib/systemd/system/apache-htcacheclean.service.
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.
invoke-rc.d: initscript apache2, action "start" failed.
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset:enabled)
   Active: failed (Result: exit-code) since Mon 2020-03-09 02:08:51 CET; 22ms ago
     Docs: https://httpd.apache.org/docs/2.4/
  Process: 637 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

mar 09 02:08:51 PotatoServer apachectl[637]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
mar 09 02:08:51 PotatoServer apachectl[637]: no listening sockets available, shutting down
mar 09 02:08:51 PotatoServer apachectl[637]: AH00015: Unable to open logs
mar 09 02:08:51 PotatoServer apachectl[637]: Action 'start' failed.
mar 09 02:08:51 PotatoServer apachectl[637]: The Apache error log may have more             information.
mar 09 02:08:51 PotatoServer systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE
mar 09 02:08:51 PotatoServer systemd[1]: apache2.service: Failed with result 'exit-code'.
mar 09 02:08:51 PotatoServer systemd[1]: Failed to start The Apache HTTP Server.
Elaborazione dei trigger per man-db (2.8.5-2)...
Elaborazione dei trigger per systemd (241-7~deb10u3+rpi1)...
}```

Body:
Pihole uses Lighttpd as its webserver which defaults to listening to listing on port 80.  Apache also listens on port 80 which is why you are getting the following error.

mar 09 02:08:51 PotatoServer apachectl[637]: (98)Address already in
  use: AH00072: make_sock: could not bind to address [::]:80 mar 09
  02:08:51 PotatoServer apachectl[637]: (98)Address already in use:
  AH00072: make_sock: could not bind to address 0.0.0.0:80 mar 09
  02:08:51 PotatoServer apachectl[637]: no listening sockets available,
  shutting down mar 09 02:08:51 PotatoServer apachectl[637]: AH00015:
  Unable to open logs mar 09 02:08:51 PotatoServer apachectl[637]:
  Action 'start' failed.

To resolve this you would need to change the port that either Apache or Lighttpd are listening on.  To change Apache's default port on raspbian:

nano /etc/apache2/ports.conf

Change Listen 80 to something else like Listen 8080.  Then hit ctrl-x and y to close and save the file.  Now you also need to change the virtual host statement.  For the default installation you can do this by editing 000-default.conf.

nano /etc/apache2/sites-enabld/000-default.conf

Change VirtualHost *:80 to VirtualHost *:8080.  Then close and save the file again.

Finally, start Apache.

sudo /etc/init.d/apache2 start


问:
javax validation constraints not working in Spring Boot
I cannot get annotations such as @NotEmpty, @NotBlank and @NotNull to fire in my Spring Boot application.

I've followed this (maven) example:

https://spring.io/guides/gs/validating-form-input/

...and I don't see what I am doing wrong.

POJO:

```<code>import javax.validation.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
    @NotBlank
    private String collegeCode;
.
.
.
</code>```

Spring controller:

```<code>@RequestMapping(value="/addCollege", method = RequestMethod.POST)
public String addCollege(@Valid @ModelAttribute("college") College college, BindingResult bindingResult, Model model, HttpSession session)
{
    if(bindingResult.hasErrors()) //this is never true
    {
        logger.debug("Errors when adding new college!!!");
        return "admin/colleges/addCollege";
    }
    collegeProcessor.saveCollege(college);
    return getAllColleges(model, session);
}
</code>```

Screen:

```<code><form action="#" th:action="${addOrEdit} == 'add' ? @{/addCollege} : @{/updateCollege}" th:object="${college}" method="post">

    <table class="table">

        <tr>
            <td>College Code</td>
            <td><input size="10" name="collegeCode" th:field="*{collegeCode}"/></td>
            <div id="errors" th:if="${#fields.hasErrors('collegeCode')}" th:errors="*{collegeCode}"></div>
        </tr>
.
.
.

</code>```

As well as @NotBlank, I have tried @NotEmpty and @NotNull, but the same thing happens.  My screen does not validate the input, and allows a college object with an empty collegeCode to be saved.

The interesting thing is if I change my POJO to use the deprecated Hibernate validator instead...

```<code>import org.hibernate.validator.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
    @NotBlank
    private String collegeCode;
.
.
.
</code>```

...then the validation DOES fire, and the screen prevents me from saving a College object with an empty collegeCode.

Can anyone tell me why my validation doesn't work when using the javax.validation.constraints validators?

答:
Since version 2.3.0.RELEASE the validation starter is not included in web/webflux starters by default, you need to add it manually. More details here</p>

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</code>```

Body:
I cannot get annotations such as @NotEmpty, @NotBlank and @NotNull to fire in my Spring Boot application.

I've followed this (maven) example:

https://spring.io/guides/gs/validating-form-input/

...and I don't see what I am doing wrong.

POJO:

import javax.validation.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
    @NotBlank
    private String collegeCode;
.
.
.

Spring controller:

@RequestMapping(value="/addCollege", method = RequestMethod.POST)
public String addCollege(@Valid @ModelAttribute("college") College college, BindingResult bindingResult, Model model, HttpSession session)
{
    if(bindingResult.hasErrors()) //this is never true
    {
        logger.debug("Errors when adding new college!!!");
        return "admin/colleges/addCollege";
    }
    collegeProcessor.saveCollege(college);
    return getAllColleges(model, session);
}

Screen:

<form action="#" th:action="${addOrEdit} == 'add' ? @{/addCollege} : @{/updateCollege}" th:object="${college}" method="post">

            College Code
            <input size="10" name="collegeCode" th:field="*{collegeCode}"/>

.
.
.

As well as @NotBlank, I have tried @NotEmpty and @NotNull, but the same thing happens.  My screen does not validate the input, and allows a college object with an empty collegeCode to be saved.

The interesting thing is if I change my POJO to use the deprecated Hibernate validator instead...

import org.hibernate.validator.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
    @NotBlank
    private String collegeCode;
.
.
.

...then the validation DOES fire, and the screen prevents me from saving a College object with an empty collegeCode.

Can anyone tell me why my validation doesn't work when using the javax.validation.constraints validators?

Body:
Since version 2.3.0.RELEASE the validation starter is not included in web/webflux starters by default, you need to add it manually. More details here

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>


问:
concatenating columns in a dataframe pyspark with null values
```<code>Data:
Name1            Name2            Name3(Expected)
RR Industries    null            RR Industries
RR Industries    RR Industries   RR IndustriesRR Industries
</code>```

Code:

```<code>.withColumn("Name3",F.concat(F.trim(Name1), F.trim(Name2)))
</code>```

Actual result:
The columns with null values are deleted.
I want the output to be as seen in Name3(Expected Columnt)

I think, the issue occurs after the joining the tables
The name column is available in df2 and df3.
before joining they do not contain null values.

Issue:
After joining; since pyspark doesnt delete the common columns, we have two name1 columns from 2 tables
I tried replcaing it with empty string;it didnt work and throws error

How do I replace null values with empty string after joining tables

```<code>df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('name1',F.when(df2('name1').isNull(),'').otherwise(df2('name1')))\
.withColumn('name1',F.when(df3('name1').isNull(),'').otherwise(df3('name1')))\
.withColumn("Name1",F.concat(F.trim(df2.name1), F.trim(df3.name1)))
</code>```

答:
Try this-

It should be implemented in python with minimal change

   val data =
      """
        |Name1         |   Name2
        |RR Industries |
        |RR Industries |   RR Industries
      """.stripMargin

    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()

    /**
      * +-------------+-------------+
      * |Name1        |Name2        |
      * +-------------+-------------+
      * |RR Industries|null         |
      * |RR Industries|RR Industries|
      * +-------------+-------------+
      *
      * root
      * |-- Name1: string (nullable = true)
      * |-- Name2: string (nullable = true)
      */
    df.withColumn("Name3(Expected)", concat_ws("", df.columns.map(col).map(c => coalesce(c, lit(""))): _*))
      .show(false)

    /**
      * +-------------+-------------+--------------------------+
      * |Name1        |Name2        |Name3(Expected)           |
      * +-------------+-------------+--------------------------+
      * |RR Industries|null         |RR Industries             |
      * |RR Industries|RR Industries|RR IndustriesRR Industries|
      * +-------------+-------------+--------------------------+
      */
    df.withColumn("Name3(Expected)", concat_ws("", df.columns.map(col): _*))
      .show(false)

    /**
      * +-------------+-------------+--------------------------+
      * |Name1        |Name2        |Name3(Expected)           |
      * +-------------+-------------+--------------------------+
      * |RR Industries|null         |RR Industries             |
      * |RR Industries|RR Industries|RR IndustriesRR Industries|
      * +-------------+-------------+--------------------------+
      */
```

Body:
Data:
Name1            Name2            Name3(Expected)
RR Industries    null            RR Industries
RR Industries    RR Industries   RR IndustriesRR Industries

Code:

.withColumn("Name3",F.concat(F.trim(Name1), F.trim(Name2)))

Actual result:
The columns with null values are deleted.
I want the output to be as seen in Name3(Expected Columnt)

I think, the issue occurs after the joining the tables
The name column is available in df2 and df3.
before joining they do not contain null values.

Issue:
After joining; since pyspark doesnt delete the common columns, we have two name1 columns from 2 tables
I tried replcaing it with empty string;it didnt work and throws error

How do I replace null values with empty string after joining tables

df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('name1',F.when(df2('name1').isNull(),'').otherwise(df2('name1')))\
.withColumn('name1',F.when(df3('name1').isNull(),'').otherwise(df3('name1')))\
.withColumn("Name1",F.concat(F.trim(df2.name1), F.trim(df3.name1)))


问:
Extra variable assignment in VHDL code makes it not work and get error "can't infer register" and "couldn't implement registers"
I am facing a error in the code below every time I got an extra "i2c_send_flag<='1';" line inside my process.

I don't understand why the code works before I add this line and stop working after I add it.

```<code>LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

ENTITY MAIN IS
    PORT(
        PIN_CLOCK_50MHZ : IN std_logic;
        PIN_KEY             : IN std_logic_vector (3 downto 0);
        LEDR                : OUT std_logic_vector (17 downto 0):="000000000000000000";
        LEDG                : OUT std_logic_vector (8 downto 0):="000000000";
        PIN_SW            : IN std_logic_vector (2 downto 0);
        PIN_I2C_SCLK        : OUT std_logic;
        PIN_I2C_SDA         : INOUT std_logic;
        PIN_MCLK                : OUT std_logic;
        PIN_BCLK                : OUT std_logic;
        PIN_ADC_DATA        : IN std_logic;
        PIN_ADC_LRCK        : OUT std_logic;
        PIN_DAC_DATA        : OUT std_logic;
        PIN_DAC_LRCK        : OUT std_logic
    );
END MAIN;

ARCHITECTURE main OF MAIN IS

    SIGNAL i2c_busy      : std_logic;
    SIGNAL i2c_send_flag : std_logic;
    SIGNAL i2c_data      : std_logic_vector(15 downto 0);
    SIGNAL i2c_done     : std_logic;
    SIGNAL clock_12mhz      : std_logic;
    SIGNAL clock_2m4hz          : std_logic;
    SIGNAL clock_100hz      : std_logic;
    SIGNAL clock_6mhz           : std_logic;
    SIGNAL adc_dac_bclk     : std_logic;
    SIGNAL adc_data         : std_logic;
    SIGNAL adc_lrck         : std_logic;
    SIGNAL dac_data         : std_logic;
    SIGNAL dac_lrck         : std_logic;

    COMPONENT i2c IS
        PORT(
            I2C_CLOCK_12MHZ: IN std_logic                               :='0';
            I2C_DEVICE_ADDR: IN std_logic_vector (7 downto 0)   :="00000000";
            I2C_DATA            : IN std_logic_vector (15 downto 0) :="0000000000000000";

            I2C_START_FLAG  : IN std_logic                              :='0';
            I2C_BUSY            : OUT std_logic                         :='0';
            I2C_DONE            : OUT std_logic                         :='0';

            I2C_SCLK            : OUT std_logic                         :='1';
            I2C_SDA         : INOUT std_logic                           :='1'
        );
    END COMPONENT i2c;

    COMPONENT pll IS
        PORT (
            inclk0  : IN STD_LOGIC  := '0';
            c0          : OUT STD_LOGIC
        );
    END COMPONENT pll;

    COMPONENT divclk_12M_2M4 IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_2M4;

    COMPONENT divclk_12M_100 IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_100;

    COMPONENT divclk_12M_6M IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_6M;

    COMPONENT adc_dac_controller IS
        PORT(
            CTRL_BCLK       :  IN std_logic;

            CTRL_ADC_DATA   :  IN  std_logic;
            CTRL_ADC_LRCK   :  OUT std_logic;

            CTRL_DAC_DATA   :  OUT std_logic;
            CTRL_DAC_LRCK   :  OUT std_logic
        );
    END COMPONENT adc_dac_controller;

    BEGIN

            WM8731: COMPONENT i2c
                            PORT MAP(
                                I2C_CLOCK_12MHZ=>   clock_12mhz,
                                I2C_DEVICE_ADDR=>   "00110100",
                                I2C_DATA            =>  i2c_data,

                                I2C_START_FLAG  =>  i2c_send_flag,
                                I2C_BUSY            =>  i2c_busy,

                                I2C_DONE            =>  i2c_done,

                                I2C_SCLK            =>  PIN_I2C_SCLK,
                                I2C_SDA         =>  PIN_I2C_SDA
                            );
            PLL12:  COMPONENT pll
                            PORT MAP(
                                inclk0          =>  PIN_CLOCK_50MHZ,
                                c0                  =>  clock_12mhz
                            );

            Divclk_2M4Hz:   COMPONENT divclk_12M_2M4
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_2m4hz
                                    );
            Divclk_6MHz:    COMPONENT divclk_12M_6M
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_6mhz
                                    );
            Divclk_100Hz:   COMPONENT divclk_12M_100
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_100hz
                                    );

            adc_dac_ctrl:   COMPONENT adc_dac_controller
                                    PORT MAP(

                                        CTRL_BCLK       => clock_12mhz,

                                        CTRL_ADC_DATA   => adc_data,
                                        CTRL_ADC_LRCK   => adc_lrck,

                                        CTRL_DAC_DATA   => dac_data,
                                        CTRL_DAC_LRCK   => dac_lrck
                                    );

    PIN_MCLK        <= clock_12mhz;
    PIN_BCLK        <= clock_12mhz;
    adc_data        <= PIN_ADC_DATA;
    PIN_ADC_LRCK<= adc_lrck;
    PIN_DAC_DATA<= dac_data;
    PIN_DAC_LRCK<= dac_lrck;
    LEDG(7)     <= i2c_done;

    PROCESS (clock_100hz)
    BEGIN

        IF rising_edge (clock_100hz) THEN
            IF (PIN_KEY="1111") THEN
                 i2c_send_flag <='0';
            END IF;
        END IF;

        IF rising_edge(clock_100hz) AND i2c_busy='0' THEN

            IF (PIN_SW (0)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0000000";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6 downto 5)<="00";
                        i2c_data(4 downto 0)<="11111";
                        i2c_send_flag<='1';
                    ------------------------------------------------------
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0000001";
                        i2c_data(8)<='1';
                        i2c_data(7)<='0';
                        i2c_data(4 downto 0)<="11111";
                        i2c_send_flag<='1';
                    ------------------------------------------------------
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(2)='0') THEN
                        i2c_data(15 downto 9)<="0000010";
                        i2c_data(8)<='0';
                        i2c_data(7)<='1';
                        i2c_data(6 downto 0)<="1111000";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(3)='0') THEN
                        i2c_data(15 downto 9)<="0000011";
                        i2c_data(8)<='1';
                        i2c_data(7)<='1';
                        i2c_data(6 downto 0)<="1111000";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0000100";
                        i2c_data(8)<='0';
                        i2c_data(7 downto 6)<="11";
                        i2c_data(5)<='0';
                        i2c_data(4)<='1';
                        i2c_data(3)<='0';
                        i2c_data(2)<='0';
                        i2c_data(1)<='1';
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0000101";
                        i2c_data(8 downto 5)<="0000";
                        i2c_data(4)<='0';
                        i2c_data(3)<='0';
                        i2c_data(2 downto 1)<="11";
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(2)='0') THEN
                        i2c_data(15 downto 9)<="0000110";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='1';
                        i2c_data(5)<='1';
                        i2c_data(4)<='0';
                        i2c_data(3)<='0';
                        i2c_data(2)<='0';
                        i2c_data(1)<='1';
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(3)='0') THEN
                        i2c_data(15 downto 9)<="0000111";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='0';
                        i2c_data(5)<='0';
                        i2c_data(4)<='1';
                        i2c_data(3 downto 2)<="00";
                        i2c_data(1 downto 0)<="10";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (2)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0001000";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='0';
                        i2c_data(5 downto 2)<="0000";
                        i2c_data(1)<='0';
                        i2c_data(0)<='1';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (2)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0001001";
                        i2c_data(8 downto 1)<="00000000";
                        i2c_data(0)<='1';
                        i2c_send_flag<='1';
--          ELSIF (PIN_SW (2)='1' AND PIN_KEY(3)='0') THEN
--                      i2c_data(15 downto 9)<="0001111";
--                      i2c_data(8 downto 0)<="000000000";
--                      i2c_data(15 downto 0)<="0001111000000000";
--                      i2c_send_flag<='1';
            END IF;

        END IF;
    END PROCESS;

END main;
</code>```

When I Uncomment the last part of code in the If statment I get the following erros:

Error (10821): HDL error at MAIN.vhd(304): can't infer register for "i2c_send_flag" because its behavior does not match any supported register model

Error (10822): HDL error at MAIN.vhd(298): couldn't implement registers for assignments on this clock edge

I can't understand why this piecce of code (which i use in the "Elsif" below and work) fail when I added it one more time.

答:
Generally speaking to make the synthesis tools happy, you need one clock per process and no logic in the clock statement.   Applied to your code it would need to be restructured as:</p>

```<code>PROCESS (clock_100hz)
BEGIN

    IF rising_edge (clock_100hz) THEN
        IF (PIN_KEY="1111") THEN
             i2c_send_flag <='0';
        END IF;
        if i2c_busy='0' THEN

          IF (PIN_SW (0)='1' AND PIN_KEY(0)='0') THEN
                    i2c_data(15 downto 9)<="0000000";
                    i2c_data(8)<='0';
                    i2c_data(7)<='0';
                    i2c_data(6 downto 5)<="00";
                    i2c_data(4 downto 0)<="11111";
                    i2c_send_flag<='1';
                ------------------------------------------------------
          ELSIF (PIN_SW (0)='1' AND PIN_KEY(1)='0') THEN
                    i2c_data(15 downto 9)<="0000001";
                    i2c_data(8)<='1';
                    i2c_data(7)<='0';
                    i2c_data(4 downto 0)<="11111";
                    i2c_send_flag<='1';
          ELSIF ...
                ...
          END IF;
        END IF;
      END IF;
</code>```

Body:
I am facing a error in the code below every time I got an extra "i2c_send_flag<='1';" line inside my process.

I don't understand why the code works before I add this line and stop working after I add it.

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

ENTITY MAIN IS
    PORT(
        PIN_CLOCK_50MHZ : IN std_logic;
        PIN_KEY             : IN std_logic_vector (3 downto 0);
        LEDR                : OUT std_logic_vector (17 downto 0):="000000000000000000";
        LEDG                : OUT std_logic_vector (8 downto 0):="000000000";
        PIN_SW            : IN std_logic_vector (2 downto 0);
        PIN_I2C_SCLK        : OUT std_logic;
        PIN_I2C_SDA         : INOUT std_logic;
        PIN_MCLK                : OUT std_logic;
        PIN_BCLK                : OUT std_logic;
        PIN_ADC_DATA        : IN std_logic;
        PIN_ADC_LRCK        : OUT std_logic;
        PIN_DAC_DATA        : OUT std_logic;
        PIN_DAC_LRCK        : OUT std_logic
    );
END MAIN;

ARCHITECTURE main OF MAIN IS

    SIGNAL i2c_busy      : std_logic;
    SIGNAL i2c_send_flag : std_logic;
    SIGNAL i2c_data      : std_logic_vector(15 downto 0);
    SIGNAL i2c_done     : std_logic;
    SIGNAL clock_12mhz      : std_logic;
    SIGNAL clock_2m4hz          : std_logic;
    SIGNAL clock_100hz      : std_logic;
    SIGNAL clock_6mhz           : std_logic;
    SIGNAL adc_dac_bclk     : std_logic;
    SIGNAL adc_data         : std_logic;
    SIGNAL adc_lrck         : std_logic;
    SIGNAL dac_data         : std_logic;
    SIGNAL dac_lrck         : std_logic;

    COMPONENT i2c IS
        PORT(
            I2C_CLOCK_12MHZ: IN std_logic                               :='0';
            I2C_DEVICE_ADDR: IN std_logic_vector (7 downto 0)   :="00000000";
            I2C_DATA            : IN std_logic_vector (15 downto 0) :="0000000000000000";

            I2C_START_FLAG  : IN std_logic                              :='0';
            I2C_BUSY            : OUT std_logic                         :='0';
            I2C_DONE            : OUT std_logic                         :='0';

            I2C_SCLK            : OUT std_logic                         :='1';
            I2C_SDA         : INOUT std_logic                           :='1'
        );
    END COMPONENT i2c;

    COMPONENT pll IS
        PORT (
            inclk0  : IN STD_LOGIC  := '0';
            c0          : OUT STD_LOGIC
        );
    END COMPONENT pll;

    COMPONENT divclk_12M_2M4 IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_2M4;

    COMPONENT divclk_12M_100 IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_100;

    COMPONENT divclk_12M_6M IS
        PORT (
            clk_in   : IN std_logic;
            clk_out  : OUT std_logic
        );
    END COMPONENT divclk_12M_6M;

    COMPONENT adc_dac_controller IS
        PORT(
            CTRL_BCLK       :  IN std_logic;

            CTRL_ADC_DATA   :  IN  std_logic;
            CTRL_ADC_LRCK   :  OUT std_logic;

            CTRL_DAC_DATA   :  OUT std_logic;
            CTRL_DAC_LRCK   :  OUT std_logic
        );
    END COMPONENT adc_dac_controller;

    BEGIN

            WM8731: COMPONENT i2c
                            PORT MAP(
                                I2C_CLOCK_12MHZ=>   clock_12mhz,
                                I2C_DEVICE_ADDR=>   "00110100",
                                I2C_DATA            =>  i2c_data,

                                I2C_START_FLAG  =>  i2c_send_flag,
                                I2C_BUSY            =>  i2c_busy,

                                I2C_DONE            =>  i2c_done,

                                I2C_SCLK            =>  PIN_I2C_SCLK,
                                I2C_SDA         =>  PIN_I2C_SDA
                            );
            PLL12:  COMPONENT pll
                            PORT MAP(
                                inclk0          =>  PIN_CLOCK_50MHZ,
                                c0                  =>  clock_12mhz
                            );

            Divclk_2M4Hz:   COMPONENT divclk_12M_2M4
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_2m4hz
                                    );
            Divclk_6MHz:    COMPONENT divclk_12M_6M
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_6mhz
                                    );
            Divclk_100Hz:   COMPONENT divclk_12M_100
                                    PORT MAP(
                                        clk_in  =>  clock_12mhz,
                                        clk_out =>  clock_100hz
                                    );

            adc_dac_ctrl:   COMPONENT adc_dac_controller
                                    PORT MAP(

                                        CTRL_BCLK       => clock_12mhz,

                                        CTRL_ADC_DATA   => adc_data,
                                        CTRL_ADC_LRCK   => adc_lrck,

                                        CTRL_DAC_DATA   => dac_data,
                                        CTRL_DAC_LRCK   => dac_lrck
                                    );

    PIN_MCLK        <= clock_12mhz;
    PIN_BCLK        <= clock_12mhz;
    adc_data        <= PIN_ADC_DATA;
    PIN_ADC_LRCK<= adc_lrck;
    PIN_DAC_DATA<= dac_data;
    PIN_DAC_LRCK<= dac_lrck;
    LEDG(7)     <= i2c_done;

    PROCESS (clock_100hz)
    BEGIN

        IF rising_edge (clock_100hz) THEN
            IF (PIN_KEY="1111") THEN
                 i2c_send_flag <='0';
            END IF;
        END IF;

        IF rising_edge(clock_100hz) AND i2c_busy='0' THEN

            IF (PIN_SW (0)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0000000";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6 downto 5)<="00";
                        i2c_data(4 downto 0)<="11111";
                        i2c_send_flag<='1';
                    ------------------------------------------------------
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0000001";
                        i2c_data(8)<='1';
                        i2c_data(7)<='0';
                        i2c_data(4 downto 0)<="11111";
                        i2c_send_flag<='1';
                    ------------------------------------------------------
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(2)='0') THEN
                        i2c_data(15 downto 9)<="0000010";
                        i2c_data(8)<='0';
                        i2c_data(7)<='1';
                        i2c_data(6 downto 0)<="1111000";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (0)='1' AND PIN_KEY(3)='0') THEN
                        i2c_data(15 downto 9)<="0000011";
                        i2c_data(8)<='1';
                        i2c_data(7)<='1';
                        i2c_data(6 downto 0)<="1111000";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0000100";
                        i2c_data(8)<='0';
                        i2c_data(7 downto 6)<="11";
                        i2c_data(5)<='0';
                        i2c_data(4)<='1';
                        i2c_data(3)<='0';
                        i2c_data(2)<='0';
                        i2c_data(1)<='1';
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0000101";
                        i2c_data(8 downto 5)<="0000";
                        i2c_data(4)<='0';
                        i2c_data(3)<='0';
                        i2c_data(2 downto 1)<="11";
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(2)='0') THEN
                        i2c_data(15 downto 9)<="0000110";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='1';
                        i2c_data(5)<='1';
                        i2c_data(4)<='0';
                        i2c_data(3)<='0';
                        i2c_data(2)<='0';
                        i2c_data(1)<='1';
                        i2c_data(0)<='0';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (1)='1' AND PIN_KEY(3)='0') THEN
                        i2c_data(15 downto 9)<="0000111";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='0';
                        i2c_data(5)<='0';
                        i2c_data(4)<='1';
                        i2c_data(3 downto 2)<="00";
                        i2c_data(1 downto 0)<="10";
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (2)='1' AND PIN_KEY(0)='0') THEN
                        i2c_data(15 downto 9)<="0001000";
                        i2c_data(8)<='0';
                        i2c_data(7)<='0';
                        i2c_data(6)<='0';
                        i2c_data(5 downto 2)<="0000";
                        i2c_data(1)<='0';
                        i2c_data(0)<='1';
                        i2c_send_flag<='1';
            ELSIF (PIN_SW (2)='1' AND PIN_KEY(1)='0') THEN
                        i2c_data(15 downto 9)<="0001001";
                        i2c_data(8 downto 1)<="00000000";
                        i2c_data(0)<='1';
                        i2c_send_flag<='1';
--          ELSIF (PIN_SW (2)='1' AND PIN_KEY(3)='0') THEN
--                      i2c_data(15 downto 9)<="0001111";
--                      i2c_data(8 downto 0)<="000000000";
--                      i2c_data(15 downto 0)<="0001111000000000";
--                      i2c_send_flag<='1';
            END IF;

        END IF;
    END PROCESS;

END main;

When I Uncomment the last part of code in the If statment I get the following erros:

Error (10821): HDL error at MAIN.vhd(304): can't infer register for "i2c_send_flag" because its behavior does not match any supported register model

Error (10822): HDL error at MAIN.vhd(298): couldn't implement registers for assignments on this clock edge

I can't understand why this piecce of code (which i use in the "Elsif" below and work) fail when I added it one more time.

Body:
Generally speaking to make the synthesis tools happy, you need one clock per process and no logic in the clock statement.   Applied to your code it would need to be restructured as:

PROCESS (clock_100hz)
BEGIN

    IF rising_edge (clock_100hz) THEN
        IF (PIN_KEY="1111") THEN
             i2c_send_flag <='0';
        END IF;
        if i2c_busy='0' THEN

          IF (PIN_SW (0)='1' AND PIN_KEY(0)='0') THEN
                    i2c_data(15 downto 9)<="0000000";
                    i2c_data(8)<='0';
                    i2c_data(7)<='0';
                    i2c_data(6 downto 5)<="00";
                    i2c_data(4 downto 0)<="11111";
                    i2c_send_flag<='1';
                ------------------------------------------------------
          ELSIF (PIN_SW (0)='1' AND PIN_KEY(1)='0') THEN
                    i2c_data(15 downto 9)<="0000001";
                    i2c_data(8)<='1';
                    i2c_data(7)<='0';
                    i2c_data(4 downto 0)<="11111";
                    i2c_send_flag<='1';
          ELSIF ...
                ...
          END IF;
        END IF;
      END IF;


问:
Pandas right align columns with numbers after to_html()
I have a pandas dataframe that I want to export to HTML using the to_html() method. Is there a way this can be achieved with the formatters or float_format parameter? How would this look like? Could I create a function that checks if a column contains numbers only and then assign a certain class to it that can then be linked to a css style? Note that I only want columns with numbers only to be right-aligned. All other columns should note be affected. Also, the headers should all be left-aligned.

答:
This regexp will replace the tag of cells containing a float or int.

Afterwards, you should add the relevant style to your page.

```<code>import re
re.sub(r"<td>((\d)+?(.(\d)+))", r"<td class='my_class'>\1", df.to_html())
</code>```

Body:
This regexp will replace the tag of cells containing a float or int.

Afterwards, you should add the relevant style to your page.

import re
re.sub(r"<td>((\d)+?(.(\d)+))", r"<td class='my_class'>\1", df.to_html())


问:
Big-o complexity problem - Linear cumulative power

Background

I am trying to work through some problems I found from Stanfords "Design & Analysis of Algorithms" course from 2013. In particular, problem 3 from problem set 1 here.

In summary it states:

You are stuck on a desert island with a radio that can transmit a distress signal at integer power levels (i.e. 1W, 2W, 3W, etc.).

If you transmit a signal with high enough power, you will receive a response and be rescued.

Unfortunately you do not know how much power, n, is needed.

The problem requests you design an algorithm that uses Θ(n)W total power.

Being a 5pt question from problem set 1, I presume this is easier than I am finding it.

My question is

...what is this algorithm?....or how can I change my thinking to find one?

Where I'm stuck

The question states that the strategy "just increase power by 1 watt each time" will result in an Θ(n^2)W total power. Indeed, this is true, as the total power used by any n is n * (n+1) / 2.

However, I can't think of any strategy that isn't:

greater than linear; or

a strategy where I cheat by "not doing anything for a few consecutive n's".

Also, if I ignore the discreteness of the radio for a minute and analyse the problem as a continuous linear function, the total power should be generalisable to a function g(n) of the form g(n) = Kn + B (where K and B are constants). This linear function would represent the integral of the function we need to use for controlling the radio.

Then, if I take the derivative of this function, dg(n)/dn, I'm left with K. I.e. If I want to have linear total power, I should just drive the radio at a constant power for n times...but this would only result in a rescue if I happened to guess K correctly the first time.

EDIT

Yes, I had already thought of doubling etc....but the answers here pointed out the error in my thinking. I had been trying to solve the question "design an algorithm that has linear cumulative power consumption"...which I think is impossible. As pointed out by the answers, I should have thought about it as "for a given n, design an algorithm that will consume Kn"...i.e. what the question posed.

答:
I've read the assignment...
It states that the radio is capable of transmitting in integers, but it doesn't mean  you should try it one by one and go over all the integers until n.

Well, I could give you the answer but I'll try just to lead you to think about it on  your own:

Please notice that you need to transmit a signal equal or greater than n, so there is no way you are "going to far". Now, with the concepts of complexity, if you go over all the signals you'll get a series of (1+2+3+...+n) which equals to Θ(n^2), try to think of a pattern which you can skip some of those and getting a series that results a sum of Θ(n).

This task is similar to searching algorithms which naively goes for Θ(n^2), but there are algorithms reduced to less than that - you should go and explore how they work :)

If you want an approach for an answer:

 You can start with 1W and each step double it for the next transmit. That way you will do log(n) attempts, and each attempt costs i which i is the power of that attempt. So the cumulative power will be something like that: (1+2+4+8+16+...+n) which equals to 2n-1 and fits the requirement of Θ(n)


问:
ImportError: No module named 'xlrd'
I am currently using PyCharm with Python version 3.4.3 for this particular project.

This PyCharm previously had Python2.7, and I upgraded to 3.4.3.

I am trying to fetch data from an Excel file using Pandas.

Here is my code:

```<code>import pandas as pd

df = pd.read_excel("File.xls", "Sheet1")
print (df)
</code>```

When I ran this code, I am getting this error.

```<code>ImportError: No module named 'xlrd'
</code>```

I searched Stackoverflow and found some suggestions:
I tried with

```<code>pip install xlrd
</code>```

But, when I did that, the message says

```<code>"Requirement already satisfied: xlrd in ./anaconda2/usr/lib/python2.7/site-packages"
</code>```

Any suggestion?

答:
If you are facing issues in Windows then try the steps below which works for me:

go to the location %localappdata%

C:\Users\<YourSystem>\AppData\Local\Programs\Python\Python38-32\Scripts

Open cmd ternimal at this location

run pip install xlrd

Title: ImportError: No module named 'xlrd'

Body:
I am currently using PyCharm with Python version 3.4.3 for this particular project.

This PyCharm previously had Python2.7, and I upgraded to 3.4.3.

I am trying to fetch data from an Excel file using Pandas.

Here is my code:

import pandas as pd

df = pd.read_excel("File.xls", "Sheet1")
print (df)

When I ran this code, I am getting this error.

ImportError: No module named 'xlrd'

I searched Stackoverflow and found some suggestions:
I tried with

pip install xlrd

But, when I did that, the message says

"Requirement already satisfied: xlrd in ./anaconda2/usr/lib/python2.7/site-packages"

Any suggestion?


问:
Wordpress qtranslate widget won’t remove
I’m using a custom theme in Wordpress and used qtranslate for the multi language part. I activated an SSL certicate and redirected http pages to HTTPS. At that point the menu links lost their slug at the end. After founding out that qtranslate hasn’t been used for a long time I changed to qtranslate-x and followed the migration tips.
All works now and I have added the language switcher in the menu at the bottom of my page.
However, the original qtranslate widget at the top is still showing, even after I removed the widget. I can’t remember if I ever hardcoded the switcher in the header, but I can’t seem to find where it is located, so that I can remove it. Help!
The url is thaiprotect.com</p>

答: I fixed it already. Qtranslate-x changes all old qtrans strings to qtranx, so I couldn’t find it. But there was a call from my theme’s functions.php straight into the header. </p>


问:
Php carbon - add days without weeks
I have a function to add days with carbon, the problem is that I want not add days of weeks.

This is my function

```<code>function addDaysWithoutWeeks($dateTimeString='',$days=0)
{
    $date = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/Madrid');
    return $date->addDays($days);
}
</code>```

For example if I'll add 3 days to:

```<code>2018-08-24 the result should be 2018-08-29
</code>```

How to can delete or omit the weeks when add days.?

答: I know it's late and already answered but now Carbon has addWeekdays() function.

Title: Php carbon - add days without weeks

Body:
I have a function to add days with carbon, the problem is that I want not add days of weeks.

This is my function

function addDaysWithoutWeeks($dateTimeString='',$days=0)
{
    $date = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/Madrid');
    return $date->addDays($days);
}

For example if I'll add 3 days to:

2018-08-24 the result should be 2018-08-29

How to can delete or omit the weeks when add days.?


问:
Jmeter - How to Check against empty DB query
For the purpose of my test, i need to check if the query is returning empty data (nothing), then enter into another condition accordingly.

My test looks like:

execute db query

If DB, does not provides anything (empty data), then enter into the If condition.

What is the easiest way to archive that?

答:
If your SQL query returns nothing the JDBC Request sampler will generate the following JMeter Variable:

```<code>resultSet_#=0
</code>```

you can observe it yourself using Debug Sampler

If you want to run some logic when the query doesn't return the results add If Controller after the JDBC Request sampler and use the following __jexl3() function as the condition:

```<code>${__jexl3(${resultSet_#} == 0,)}
</code>```

If everything goes well If Controller's children will be executed only when the query returns empty result set:

Body:
If your SQL query returns nothing the JDBC Request sampler will generate the following JMeter Variable:

resultSet_#=0

you can observe it yourself using Debug Sampler

If you want to run some logic when the query doesn't return the results add If Controller after the JDBC Request sampler and use the following __jexl3() function as the condition:

${__jexl3(${resultSet_#} == 0,)}

If everything goes well If Controller's children will be executed only when the query returns empty result set:


问:
Why not use as.integer to check if a number is an integer?
R's is.integer notoriously does not check if the input is a whole number. Instead, it checks for integer typing. Its documentation suggests that if we want to check if something is a whole number, we should use:

```<code>is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol
</code>```

but wouldn't

```<code>is.int<-function(numb) is.numeric(numb)&&as.integer(numb)==numb
</code>```

be a cleaner method and require one less parameter? What is the advantage of is.wholenumber over is.int?

答:
Your method isn't entirely dependable.

```<code>> sqrt(999)^2
[1] 999
> is.wholenumber(sqrt(999)^2)
[1] TRUE
> is.int(sqrt(999)^2)
[1] FALSE
> options(digits =22)
> sqrt(999)^2
[1] 998.99999999999989
</code>```

If an operation that should return an integer goes through a process where it's slightly off then your method will say not an integer. Maybe that's what you want. But most people are looking for "is this reasonable to assume that this is an integer"

Body:
R's is.integer notoriously does not check if the input is a whole number. Instead, it checks for integer typing. Its documentation suggests that if we want to check if something is a whole number, we should use:

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol

but wouldn't

is.int<-function(numb) is.numeric(numb)&&as.integer(numb)==numb

be a cleaner method and require one less parameter? What is the advantage of is.wholenumber over is.int?

Body:
Your method isn't entirely dependable.

> sqrt(999)^2
[1] 999
> is.wholenumber(sqrt(999)^2)
[1] TRUE
> is.int(sqrt(999)^2)
[1] FALSE
> options(digits =22)
> sqrt(999)^2
[1] 998.99999999999989

If an operation that should return an integer goes through a process where it's slightly off then your method will say not an integer. Maybe that's what you want. But most people are looking for "is this reasonable to assume that this is an integer"