问:
Django: Can't set up custom django User model
I want to set up my own django User model because I need additional fields, but I am getting the error. I read a lot of posts but I didn't find solution. What is the problem?

Code models.py:

```<code>class User(AbstractBaseUser):
    username = models.CharField(max_length=30, unique=True),
    email = models.EmailField(max_length=50, unique=True),
    city = models.TextField(max_length=30, blank=True),
    friends = models.ManyToManyField("Account", blank=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['username']
</code>```

Code admin.py

```<code>admin.site.register(User)
</code>```

Code admin settings:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig'
]

AUTH_USER_MODEL = 'users.User'
</code>```

Error:

```<code>Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 608, in get_field
    return self.fields_map[field_name]
KeyError: 'username'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 438, in check
    all_issues = checks.run_checks(
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model
    if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any(
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 610, in get_field
    raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: User has no field named 'username'
</code>```

答:
Why you are mentioning REQUIRED_Fields

```<code>USERNAME_FIELD = 'username'
</code>```

When you don't give arguments as Null = true or blank = true as default they become required ones. So Don't Mention them
Go like this:

```<code>class User(AbstractBaseUser):
     username = models.CharField(max_length=30, unique=True),
     email = models.EmailField(max_length=50, unique=True),
     city = models.TextField(max_length=30, blank=True),
     friends = models.ManyToManyField("Account", blank=True)
</code>```

And define Your Admin.py

```<code>from .models import User
from django.contrib import admin

class UserAdmin(admin.ModelAdmin):
    list_display = ["id", "username"]

admin.site.register(User, UserAdmin)
</code>```

Body:
I want to set up my own django User model because I need additional fields, but I am getting the error. I read a lot of posts but I didn't find solution. What is the problem?

Code models.py:

class User(AbstractBaseUser):
    username = models.CharField(max_length=30, unique=True),
    email = models.EmailField(max_length=50, unique=True),
    city = models.TextField(max_length=30, blank=True),
    friends = models.ManyToManyField("Account", blank=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['username']

Code admin.py

admin.site.register(User)

Code admin settings:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig'
]

AUTH_USER_MODEL = 'users.User'

Error:

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 608, in get_field
    return self.fields_map[field_name]
KeyError: 'username'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 438, in check
    all_issues = checks.run_checks(
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model
    if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any(
  File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 610, in get_field
    raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: User has no field named 'username'

Body:
Why you are mentioning REQUIRED_Fields

USERNAME_FIELD = 'username'

When you don't give arguments as Null = true or blank = true as default they become required ones. So Don't Mention them
Go like this:

class User(AbstractBaseUser):
     username = models.CharField(max_length=30, unique=True),
     email = models.EmailField(max_length=50, unique=True),
     city = models.TextField(max_length=30, blank=True),
     friends = models.ManyToManyField("Account", blank=True)

And define Your Admin.py

from .models import User
from django.contrib import admin

class UserAdmin(admin.ModelAdmin):
    list_display = ["id", "username"]

admin.site.register(User, UserAdmin)


来源: stackexchange

问:
Is there a setting to stop the display of "No data available in table" in the DataTable?
Initially my table has no data and I get "No data available in table" which is the expected functionality.

I'd like to have no text or row created as I will be populating the table via Ajax depending on user action.

Is there a setting to stop the display of this row in the table? I can't seem to find one. This code works but the first row reads "No data available in table". This is the jQuery code:

```<code>$.ajax({
    type: 'GET',
    url: '/Home/postInformationofConferenceTitle',
    dataType: "JSON",
    success: function (data) {

        $.post("/Home/selectRooms", { xtitle: data.xglobalTitle }, function (data) {

            var ndx = 0;
            $.each(data.xroom_name, function (key, value) {

                var Xroom_name = data.xroom_name[ndx];
                var Xroom_plan = data.xroom_plan[ndx];

                var column =
                  ('<tr>' +
                    '<td>' +
                    '<div class="img-container">' +
                    '<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
                    '</div>' +
                    '</td>' +
                    '<td id="imgname">' + Xroom_name + '</td>' +
                    '<td class="text-right">' +
                    '<a href="#" class="btn btn-simple btn-warning btn-icon edit" data-toggle="modal" data-target="#myModal"><i class="fa fa-edit"></i></a>' +
                    '<a href="#" class="btn btn-simple btn-danger btn-icon remove" ><i class="fa fa-times"></i></a>' +
                    '</td>' +
                    '</tr>');

                document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;

                ndx++;

            });

        });

    }
})
</code>```

答:
Next CSS worked for me to totally hide that block (not only delete text):</p>
```<code>.dataTables_empty
{
    display:none;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Initially my table has no data and I get "No data available in table" which is the expected functionality.

I'd like to have no text or row created as I will be populating the table via Ajax depending on user action.

Is there a setting to stop the display of this row in the table? I can't seem to find one. This code works but the first row reads "No data available in table". This is the jQuery code:

$.ajax({
    type: 'GET',
    url: '/Home/postInformationofConferenceTitle',
    dataType: "JSON",
    success: function (data) {

        $.post("/Home/selectRooms", { xtitle: data.xglobalTitle }, function (data) {

            var ndx = 0;
            $.each(data.xroom_name, function (key, value) {

                var Xroom_name = data.xroom_name[ndx];
                var Xroom_plan = data.xroom_plan[ndx];

                var column =
                  ('
' +
                    '' +
                    '
' +
                    '' +
                    '
' +
                    '	' +
                    '' + Xroom_name + '	' +
                    '' +
                    '' +
                    '' +
                    '	' +
                    '
');

                document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;

                ndx++;

            });

        });

    }
})

Body:
Next CSS worked for me to totally hide that block (not only delete text):

.dataTables_empty
{
    display:none;
}

ContentLicense: CC BY-SA 4.0


问:
Filter Grouped Dataset by Another Column in dplyr
I have a dataset with multiple rows of the same individual

```<code>set.seed(420)
df <- data.frame(ind = c(rep("A",3), rep("B",5), rep("C",4)), value = seq(1:12), location = sample(c("first", "second", "third"), 12, replace = TRUE))

df
  ind value location
1    A     1    first
2    A     2    first
3    A     3   second
4    B     4   second
5    B     5    first
6    B     6    first
7    B     7    first
8    B     8    first
9    C     9    first
10   C    10    first
11   C    11    first
12   C    12    third
</code>```

I would like to find the location for each individual for which the value column is highest.

So the final dataset would like:

```<code>ind    value    location
A      3        second
B      8        first
C      12       third
</code>```

Is this possible to do with group_by and summarize or mutate in dplyr?

答:
There are a few ways to do it using tidyverse.

```<code>library(tidyverse)

df %>% group_by(ind) %>% slice_max(value)
</code>```

Or

```<code>df %>% group_by(ind) %>% filter(value == max(value))
</code>```

Addressing your question

mutate()

For mutate(), it would require extra steps to filter the data (i.e. made the data unique), since it would not shrink the data by group.

First group_by as usual,

Make sure we arrange by value, since we'll use the position to extract the location associated with maximum value

Set value column to the max(value)

Set location column to the last(location), since we've sorted the value, last(location) should be the location of the max(value)

Only keep the distinct rows

```<code>df %>% group_by(ind) %>%
  arrange(value) %>%
  mutate(value = max(value),
         location = last(location)) %>%
  distinct(value, .keep_all = T)
</code>```

summarise()

Similar logic from mutate() can be applied to summarise(), but we do not need the distinct() step, since the summarise() would naturally shrink the data by group, but remember we need  arrange(value) to make sure the values are sorted properly.

```<code>df %>% group_by(ind) %>%
  arrange(value) %>%
  summarize(value = max(value), location = last(location))
</code>```

Output

```<code># A tibble: 3 x 3
# Groups:   ind [3]
  ind   value location
  <chr> <int> <chr>
1 A         3 second
2 B         8 first
3 C        12 third
</code>```

Body:
I have a dataset with multiple rows of the same individual

set.seed(420)
df <- data.frame(ind = c(rep("A",3), rep("B",5), rep("C",4)), value = seq(1:12), location = sample(c("first", "second", "third"), 12, replace = TRUE))

df
  ind value location
1    A     1    first
2    A     2    first
3    A     3   second
4    B     4   second
5    B     5    first
6    B     6    first
7    B     7    first
8    B     8    first
9    C     9    first
10   C    10    first
11   C    11    first
12   C    12    third

I would like to find the location for each individual for which the value column is highest.

So the final dataset would like:

ind    value    location
A      3        second
B      8        first
C      12       third

Is this possible to do with group_by and summarize or mutate in dplyr?

Body:
There are a few ways to do it using tidyverse.

library(tidyverse)

df %>% group_by(ind) %>% slice_max(value)

Or

df %>% group_by(ind) %>% filter(value == max(value))

Addressing your question

mutate()

For mutate(), it would require extra steps to filter the data (i.e. made the data unique), since it would not shrink the data by group.

First group_by as usual,

Make sure we arrange by value, since we'll use the position to extract the location associated with maximum value

Set value column to the max(value)

Set location column to the last(location), since we've sorted the value, last(location) should be the location of the max(value)

Only keep the distinct rows

df %>% group_by(ind) %>%
  arrange(value) %>%
  mutate(value = max(value),
         location = last(location)) %>%
  distinct(value, .keep_all = T)

summarise()

Similar logic from mutate() can be applied to summarise(), but we do not need the distinct() step, since the summarise() would naturally shrink the data by group, but remember we need  arrange(value) to make sure the values are sorted properly.

df %>% group_by(ind) %>%
  arrange(value) %>%
  summarize(value = max(value), location = last(location))

Output

# A tibble: 3 x 3
# Groups:   ind [3]
  ind   value location
  <chr> <int> <chr>
1 A         3 second
2 B         8 first
3 C        12 third


问:
Stripe API - Search Based on Metadata
I have an application that uses a deep integration with Stripe.  My platform is occasionally charging the connected accounts and I am storing information about these charges in the metadata of the charge itself.

I want to display this information back to the connected account so I am using the Charge Service to list charges.  However I want to filter that list based on some metadata key/value pair so that I don't have to list all of the charges each time, for every connected account.

Is there a clever way of doing this?

答:
Stripe recently added Search API that allows search by metadata. Currently, it does not have .NET / C# integration but you can query using HTTP call directly:

Example from their docs:

```<code>curl https://api.stripe.com/v1/search/charges \
  -u sk_test_daHanKyJOCiXCeBsa65biLML00wylimZ8S: \
  --data-urlencode "query=metadata['key']:'value'" \
  -H "Stripe-Version: 2020-08-27;search_api_beta=v1" \
  -G
</code>```

Title: Stripe API - Search Based on Metadata

Body:
Stripe recently added Search API that allows search by metadata. Currently, it does not have .NET / C# integration but you can query using HTTP call directly:

Example from their docs:

curl https://api.stripe.com/v1/search/charges \
  -u sk_test_daHanKyJOCiXCeBsa65biLML00wylimZ8S: \
  --data-urlencode "query=metadata['key']:'value'" \
  -H "Stripe-Version: 2020-08-27;search_api_beta=v1" \
  -G


问:
Prevent Assembly.GetTypes() from loading dependencies
I have assembly A referencing assembly B. They are located in the same directory.

```<code>Type[] types = null;
try
{
  Assembly a = Assembly.Load("A.dll");
  types = a.GetTypes(); // loads B implicitly.
}
catch(ReflectionTypeLoadException ex)
{
  types = ex.Types.Where(x=>x!=null);
}
</code>```

How do I prevent B from being loaded? I want GetTypes() to run as if B wasn't available and to return only available types and null's for not available so I could execute
ex.Types.where(x=>x!=null);

I want to use the trick from How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

This way I can get only types that don't depend on B and work with them.

Update:

I loaded A in the reflection as well as in the normal context. I used the reflection context A for calling GetTypes(). After getting types from the reflection context assembly, I had another problem. When I called Type.GetCustomAttributes(), I received the following exception

It is illegal to reflect on the custom attributes of a Type loaded via
  ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use
  CustomAttributeData instead.

I solved it by getting the same type from the normal context assembly.

```<code>//... code omited for brevity
Type reflectionType = reflectionAssembly.GetTypes()[0];
//... code omited for brevity
Type goodType = normalAssembly.GetType(reflectionType.FullName);
</code>```

This way I prevented loading of B and used types from A independent from B.

答:
It's 2022, and .NET 6 is here, so the solution mentioned above is officially obsolete.

Here is a new solution:
https://github.com/dotnet/corefxlab/blob/master/docs/specs/typeloader.md

Apparently, this is an archived experimental repository, so you have to embed the code into your project manually. Take note of the license.

Body:
I have assembly A referencing assembly B. They are located in the same directory.

Type[] types = null;
try
{
  Assembly a = Assembly.Load("A.dll");
  types = a.GetTypes(); // loads B implicitly.
}
catch(ReflectionTypeLoadException ex)
{
  types = ex.Types.Where(x=>x!=null);
}

How do I prevent B from being loaded? I want GetTypes() to run as if B wasn't available and to return only available types and null's for not available so I could execute
ex.Types.where(x=>x!=null);

I want to use the trick from How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

This way I can get only types that don't depend on B and work with them.

Update:

I loaded A in the reflection as well as in the normal context. I used the reflection context A for calling GetTypes(). After getting types from the reflection context assembly, I had another problem. When I called Type.GetCustomAttributes(), I received the following exception

It is illegal to reflect on the custom attributes of a Type loaded via
  ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use
  CustomAttributeData instead.

I solved it by getting the same type from the normal context assembly.

//... code omited for brevity
Type reflectionType = reflectionAssembly.GetTypes()[0];
//... code omited for brevity
Type goodType = normalAssembly.GetType(reflectionType.FullName);

This way I prevented loading of B and used types from A independent from B.


问:
Why do I get 0 when running my "mult(num)" function?
I am a noob in Python and I got stuck with the following code. I can't figure out why my function 'mult(num') can't calculate sum 'su' even though inside the function when I run print(su, end="   ") it gives all numbers I expect?

```<code>def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su += i
            return su
            # print(su, end="   ")  when running this line I see >>>> 0   3   8   14   23   33   45   60

print(mult(18))
</code>```

output

```<code>>>>  0
</code>```

Why do I get 0?

答:
In your code, there is a problem in the indentation of return su.
The code should be corrected as follows.

```<code>def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su += i

    return su

print(mult(18))
</code>```

Note that the return su is only executed one time even it is inside a loop. That is why your code gets the output as 0.

Body:
I am a noob in Python and I got stuck with the following code. I can't figure out why my function 'mult(num') can't calculate sum 'su' even though inside the function when I run print(su, end="   ") it gives all numbers I expect?

def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su += i
            return su
            # print(su, end="   ")  when running this line I see >>>> 0   3   8   14   23   33   45   60

print(mult(18))

output

>>>  0

Why do I get 0?

Body:
In your code, there is a problem in the indentation of return su.
The code should be corrected as follows.

def mult(num):
    su = 0
    for i in range(num):
        if i % 3 == 0 or i % 5 == 0:
            su += i

    return su

print(mult(18))

Note that the return su is only executed one time even it is inside a loop. That is why your code gets the output as 0.


问:
C# Permutation of an array of arraylists?
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

```<code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code>```

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

```<code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code>```

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

答: You could use factoradics to generate the enumeration of permutations.  Try this article on MSDN for an implementation in C#.  </p>

OwnerDisplayName: TaRDy

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

OwnerDisplayName: Neil Williams


问:
Connect Timeout with Alarm()
Since it seems that I can't find a solution to my original problem, I tried to do a little workaround. I'm simply trying to set a timeout to the connect() call of my TCP Socket.

I want the connect() to be blocking but not until the usual 75 seconds timeout, I want to define my own.

I have already tried select() which worked for the timeout but I couldn't get a connection (that was my initial problem as described here ).

So now I found another way to deal with it: just do a blocking connect() call but interrupt it with an alarm like this :

```<code>    signal(SIGALRM, connect_alarm);
    int secs = 5;
    alarm(secs);
    if (connect(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) < 0 )
    {
        if ( errno == EINTR )
        {
            debug_printf("Timeout");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_TIMEOUT;
        }
        else
        {
            debug_printf("Other Err");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_NET_SOCKET;
        }
    }
</code>```

with

```<code>static void connect_alarm(int signo)
{
     debug_printf("SignalHandler");
     return;
}
</code>```

This is the solution I found on the Internet in a thread here on stackoverflow. If I use this code the program starts the timer and then goes into the connect() call. After the 5 seconds the signal handler is fired (as seen on the console with the printf()), but after that the program still remains within the connect() function for 75 seconds. Actually every description says that the connect_alarm() should interrupt the connect() function but it seems it doesn't in my case. Is there any way to get the desired result for my problem?

答: While it's relatively easy to setup the alarm(2) (less the pain of signal handling and system call interruptions), the more efficient way of timing out TCP connection attempts is the non-blocking connect, which also allows you to initiate multiple connections and wait on all of them, handling successes and failures one at a time.

Title: Connect Timeout with Alarm()

Body:
Since it seems that I can't find a solution to my original problem, I tried to do a little workaround. I'm simply trying to set a timeout to the connect() call of my TCP Socket.

I want the connect() to be blocking but not until the usual 75 seconds timeout, I want to define my own.

I have already tried select() which worked for the timeout but I couldn't get a connection (that was my initial problem as described here ).

So now I found another way to deal with it: just do a blocking connect() call but interrupt it with an alarm like this :

    signal(SIGALRM, connect_alarm);
    int secs = 5;
    alarm(secs);
    if (connect(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) < 0 )
    {
        if ( errno == EINTR )
        {
            debug_printf("Timeout");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_TIMEOUT;
        }
        else
        {
            debug_printf("Other Err");
            m_connectionStatus = STATUS_CLOSED;
            return ERR_NET_SOCKET;
        }
    }

with

static void connect_alarm(int signo)
{
     debug_printf("SignalHandler");
     return;
}

This is the solution I found on the Internet in a thread here on stackoverflow. If I use this code the program starts the timer and then goes into the connect() call. After the 5 seconds the signal handler is fired (as seen on the console with the printf()), but after that the program still remains within the connect() function for 75 seconds. Actually every description says that the connect_alarm() should interrupt the connect() function but it seems it doesn't in my case. Is there any way to get the desired result for my problem?


问:
how to create monthly and season 24 hours average table using pandas
I have a dataframe with 2 columns: Date and LMP and there are totals of 8760 rows. This is the dummy dataframe:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': pd.date_range('2023-01-01 00:00', '2023-12-31 23:00', freq='1H'), 'LMP': np.random.randint(10, 20, 8760)})
</code>```

I extract month from the date and then created the season column for the specific dates. Like this

```<code>df['month'] = pd.DatetimeIndex(df['Date']).month
season = []
for i in df['month']:
    if i <= 2 or i == 12:
        season.append('Winter')
    elif 2 < i <= 5:
        season.append('Spring')
    elif 5 < i <= 8:
        season.append('Summer')
    else:
        season.append('Autumn')
df['Season'] = season
df2 = df.groupby(['month']).mean()
df3 = df.groupby(['Season']).mean()
print(df2['LMP'])
print(df3['LMP'])
</code>```

Output:

```<code>**month**
1     20.655113
2     20.885532
3     19.416946
4     22.025248
5     26.040606
6     19.323863
7     51.117965
8     51.434093
9     21.404680
10    14.701989
11    20.009590
12    38.706160

**Season**
Autumn    18.661426
Spring    22.499365
Summer    40.856845
Winter    26.944382
</code>```

But I want the output to be in 24 hour average for both monthly and seasonal.
Desired Output:
for seasonal 24 hours average

For monthyl 24 hours average

Note: in the monthyl 24 hour average columns are months(1,2,3,4,5,6,7,8,9,10,11,12) and rows are hours(starting from 0).
Can anyone help?

答:
try:

```<code>df['hour']=pd.DatetimeIndex(df['Date']).hour
dft = df[['Season', 'hour', 'LMP']]
dftg = dft.groupby(['hour', 'Season'])['LMP'].mean()
dftg.reset_index().pivot(index='hour', columns='Season')
</code>```

result:

Body:
I have a dataframe with 2 columns: Date and LMP and there are totals of 8760 rows. This is the dummy dataframe:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': pd.date_range('2023-01-01 00:00', '2023-12-31 23:00', freq='1H'), 'LMP': np.random.randint(10, 20, 8760)})

I extract month from the date and then created the season column for the specific dates. Like this

df['month'] = pd.DatetimeIndex(df['Date']).month
season = []
for i in df['month']:
    if i <= 2 or i == 12:
        season.append('Winter')
    elif 2 < i <= 5:
        season.append('Spring')
    elif 5 < i <= 8:
        season.append('Summer')
    else:
        season.append('Autumn')
df['Season'] = season
df2 = df.groupby(['month']).mean()
df3 = df.groupby(['Season']).mean()
print(df2['LMP'])
print(df3['LMP'])

Output:

**month**
1     20.655113
2     20.885532
3     19.416946
4     22.025248
5     26.040606
6     19.323863
7     51.117965
8     51.434093
9     21.404680
10    14.701989
11    20.009590
12    38.706160

**Season**
Autumn    18.661426
Spring    22.499365
Summer    40.856845
Winter    26.944382

But I want the output to be in 24 hour average for both monthly and seasonal.
Desired Output:
for seasonal 24 hours average

For monthyl 24 hours average

Note: in the monthyl 24 hour average columns are months(1,2,3,4,5,6,7,8,9,10,11,12) and rows are hours(starting from 0).
Can anyone help?

Body:
try:

df['hour']=pd.DatetimeIndex(df['Date']).hour
dft = df[['Season', 'hour', 'LMP']]
dftg = dft.groupby(['hour', 'Season'])['LMP'].mean()
dftg.reset_index().pivot(index='hour', columns='Season')

result:


问:
Pip freeze for only project requirements
When I run pip freeze > requirements.txt it seems to include all installed packages. This appears to be the documented behavior.

I have, however, done something wrong as this now includes things like Django in projects that have no business with Django.

How do I get requirements for just this project? or in the future how do I install a package with pip to be used for this project. I think I missed something about a virtualenv.

答:
I still suggest using the official pip freeze > requirements.txt (documentation) compared to the two alternative features using pigar and pipreqs mentioned in the other answers because pip freeze lists the effective package names.

Incomplete comparison among the three as per February 2022

Criteria \ Tool
pip freeze > requirements.txt
pigar
pipreqs

Name mismatch (1)
Package my-package==1.0.0
Module my_package == 1.0.0
Module my_package==1.0.0

Module overloading (2)
All packages my-package1==1.0.0, my-package2==2.0.0
None
Top-level module (version shows 0.0.0) my==0.0.0

Showing only directly used packages
No
Yes
Yes

Minimal contents
Yes
No
Yes

(1) There can be a mismatch between module and package name such as my-package (package name) vs my_package (module name).

(2) There can be several packages using the same top level folder such as my-package1 and my-package2 (package names) which are installed under my/package1 and my/package2, which are imported by Python's command import my.package1 and import my.package2. Note that pipreqs notes version 0.0.0 for the not existing package my.

I know these are very particular cases but I hope giving people this overview can help understanding limitations and avoid possible mistakes.


问:
How to pass a parameter to a usercontrol in a repeater
I have a usercontroll which accepts some parameter and I need to insert this usercontrol in repeater and pass a parameter from List<> to each one, I'm doing it like this:

```<code><asp:Repeater ID="winnersRepeater" runat="server">
  <ItemTemplate>
    <uc:myControl ID="myControl" NodeId="<%# DataBinder.Eval(Container.DataItem,"Id")%>" runat="server" />
  </ItemTemplate>
</asp:Repeater>
</code>```

I do binding in PageLoad:

```<code>List<Winner> winners = new List<Winner>();
//...
winnersRepeater.DataSource = winners;
winnersRepeater.DataBind();
</code>```

It doesn't work, I'm getting Error creating usercontrol... The server tag is not well formed.

How can I do it? thanks

答: You could handle the ItemDataBound event of the Repeater. In your handler you should be able to do FindControl("myControl") and pass to it the NodeId value without having to declare it in the mark-up.</p>

Body:
I have a usercontroll which accepts some parameter and I need to insert this usercontrol in repeater and pass a parameter from List<> to each one, I'm doing it like this:

<asp:Repeater ID="winnersRepeater" runat="server">
  <ItemTemplate>
    <uc:myControl ID="myControl" NodeId="<%# DataBinder.Eval(Container.DataItem,"Id")%>" runat="server" />
  </ItemTemplate>
</asp:Repeater>

I do binding in PageLoad:

List<Winner> winners = new List<Winner>();
//...
winnersRepeater.DataSource = winners;
winnersRepeater.DataBind();

It doesn't work, I'm getting Error creating usercontrol... The server tag is not well formed.

How can I do it? thanks


问:
Pandas Dataframe object types fillna exception over different datatypes
I have a Pandas Dataframe with different dtypes for the different columns.   E.g.  df.dtypes returns the following.

```<code>Date                    datetime64[ns]
FundID                           int64
FundName                        object
CumPos                           int64
MTMPrice                       float64
PricingMechanism                object
</code>```

Various of cheese columns have missing values in them.  Doing a group operations on it with NaN values in place cause problems.  To get rid of them with the .fillna() method is the obvious choice. Problem is the obvious clouse for strings are .fillna("")  while  .fillna(0) is the correct choice for ints and floats.   Using either method on DataFrame throws exception.   Any elegant solutions besides doing them individually (have about 30 columns)?   I have a lot of code depending on the DataFrame and would prefer not to retype the columns as it is likely to break some other logic.
Can do:

```<code>df.FundID.fillna(0)
df.FundName.fillna("")
etc
</code>```

答:
Rather than running the conversion one column at a time, which is inefficient, here is a way to grab all of the int or float columns and change in one shot.

```<code>int_float_cols = df.select_dtypes(include=['int', 'float']).columns
df[int_float_cols] = df[int_float_cols].fillna(value=0)
</code>```

Obvious how to adapt this to handle object.

I'm aware that in Pandas older versions, there were no NAs allowed in integers, so grabbing the "ints" is not strictly necessary and it may accidentially promote ints to floats. However, in our use case, it is better to be safe than sorry.

I ran into this because ordinary approach, df.fillna(0) corrupted all of the datetime variables.

Body:
I have a Pandas Dataframe with different dtypes for the different columns.   E.g.  df.dtypes returns the following.

Date                    datetime64[ns]
FundID                           int64
FundName                        object
CumPos                           int64
MTMPrice                       float64
PricingMechanism                object

Various of cheese columns have missing values in them.  Doing a group operations on it with NaN values in place cause problems.  To get rid of them with the .fillna() method is the obvious choice. Problem is the obvious clouse for strings are .fillna("")  while  .fillna(0) is the correct choice for ints and floats.   Using either method on DataFrame throws exception.   Any elegant solutions besides doing them individually (have about 30 columns)?   I have a lot of code depending on the DataFrame and would prefer not to retype the columns as it is likely to break some other logic.
Can do:

df.FundID.fillna(0)
df.FundName.fillna("")
etc

Body:
Rather than running the conversion one column at a time, which is inefficient, here is a way to grab all of the int or float columns and change in one shot.

int_float_cols = df.select_dtypes(include=['int', 'float']).columns
df[int_float_cols] = df[int_float_cols].fillna(value=0)

Obvious how to adapt this to handle object.

I'm aware that in Pandas older versions, there were no NAs allowed in integers, so grabbing the "ints" is not strictly necessary and it may accidentially promote ints to floats. However, in our use case, it is better to be safe than sorry.

I ran into this because ordinary approach, df.fillna(0) corrupted all of the datetime variables.


问:
While loop is running even though one of the conditions by the and is false
```<code>spam = 1
lam = ""

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")
</code>```

After I put 2 as my input lam = 2 making the condition false. However it still runs 4 more times due to the spam instead of ending.

答:
You need to typecast lam to int since you are comparing it to 2.
Try in this way:

```<code>spam = 1
lam = 0

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = int(input())
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
    print("You got it wrong")
</code>```

Body:
spam = 1
lam = ""

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")

After I put 2 as my input lam = 2 making the condition false. However it still runs 4 more times due to the spam instead of ending.

Body:
You need to typecast lam to int since you are comparing it to 2.
Try in this way:

spam = 1
lam = 0

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = int(input())
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
    print("You got it wrong")


问:
Safari change the color of the Background (search bar)
When visiting my website on safari it shows a purple pink color in the background/ behind the search bar.

How can I turn this off or change the color using html/css/js?

Thank you

答:
figured out the answer:

Using

<meta content="#bcbbff" data-react-helmet="true" name="theme-color" />
```

we can change the color of Safari's background.

Body:
figured out the answer:

Using

<meta content="#bcbbff" data-react-helmet="true" name="theme-color" />

we can change the color of Safari's background.


问:
How can I spy on a function from setup in vuejs3?
I have a function in my component inside of setup():

export default defineComponent({
  setup() {
    const handleResume = async () => {
      msg.value = {}
      try {
      } catch (err) {
      }
    }
    return { handleResume }
  }
})
```
<p>Now in my test, I want to create a spy function like this:</p>
<pre class="lang-js prettyprint-override"><code>import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')
</code>```

But I am getting this error:

```<code>Cannot spy the handleResume property because it is not a function; undefined given instead
</code>```

答:
you have to switch setup from object to function which return object. So your setup should looks like this:

setup() {
  const handleResume = async () => {
        msg.value = {}
        try {

        } catch (err) {

        }
      }

  return { handleResume }
}
     ```

After this you have two options, you can use @vue/test-utils, mount component as wrapper in test file and you should get access to your function by wrapper.vm.handleResume. Other solution, you can export your setup to composable and import composable into test instead of mounting component.

Body:
I have a function in my component inside of setup():

export default defineComponent({
  setup() {
    const handleResume = async () => {
      msg.value = {}
      try {
      } catch (err) {
      }
    }
    return { handleResume }
  }
})

Now in my test, I want to create a spy function like this:

import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')

But I am getting this error:

Cannot spy the handleResume property because it is not a function; undefined given instead

Body:
you have to switch setup from object to function which return object. So your setup should looks like this:

setup() {
  const handleResume = async () => {
        msg.value = {}
        try {

        } catch (err) {

        }
      }

  return { handleResume }
}

After this you have two options, you can use @vue/test-utils, mount component as wrapper in test file and you should get access to your function by wrapper.vm.handleResume. Other solution, you can export your setup to composable and import composable into test instead of mounting component.


问:
How to roll the rows of a Eigen:Matrix?
I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N=+1):

```
1 4 7  ->  3 6 9
2 5 8      1 4 7
3 6 9      2 5 8
```

Is there a simple way, or do I have to create a new matrix and copy over the data?

答:
If you are interested in a matlab-like syntax you can also use

MatrixXd A;
//... fill A
VectorXi indices = {{2,0,1}};

A(indices, Eigen::all);
```

I don't know, whether this internally makes a copy.

Note: This does not work for Sparse matrices, see Subset columns of sparse eigen matrix

Title: How to roll the rows of a Eigen:Matrix?

Body:
I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N=+1):

1 4 7  ->  3 6 9
2 5 8      1 4 7
3 6 9      2 5 8

Is there a simple way, or do I have to create a new matrix and copy over the data?

Body:
If you are interested in a matlab-like syntax you can also use

MatrixXd A;
//... fill A
VectorXi indices = {{2,0,1}};

A(indices, Eigen::all);

I don't know, whether this internally makes a copy.

Note: This does not work for Sparse matrices, see Subset columns of sparse eigen matrix


问:
Javascript matching objects of an array
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

```<code>const allaOrter = orter.map((allOrt) =>
<li>{allOrt.url}</li>
)
</code>```

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

```<code>orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]
</code>```

答:
Use array.prototype.filter method then map the returned array</p>
```<code>const arr = [{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

let filtered = (a) => a.url.includes("/blekinge")

console.log(arr.filter(filtered))

then map the result
</code>```

Title: Javascript matching objects of an array

Body:
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

const allaOrter = orter.map((allOrt) =>

{allOrt.url}

)

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

Body:
Use array.prototype.filter method then map the returned array

const arr = [{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

let filtered = (a) => a.url.includes("/blekinge")

console.log(arr.filter(filtered))

then map the result


问:
React native Error: The HTTP/S server is already being used by another WebSocket server
I'm trying to run yarn start, not working for me. I have tried changing port but it gives the same result.

┌──────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│  Running Metro Bundler on port 8084.                                         │
│                                                                              │
│  Keep Metro running while developing on any JS projects. Feel free to        │
│  close this tab and run your own Metro instance if you prefer.               │
│                                                                              │
│  https://github.com/facebook/react-native                                    │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

warning: the transform cache was reset.
master/node_modules/ws/lib/websocket-server.js:83
        throw new Error(
        ^

Error: The HTTP/S server is already being used by another WebSocket server
    at new WebSocketServer (/node_modules/ws/lib/websocket-server.js:83:15)
    at InspectorProxy._addDeviceConnectionHandler (/node_modules/metro-inspector-proxy/src/InspectorProxy.js:220:17)
    at InspectorProxy.addWebSocketListener (/node_modules/metro-inspector-proxy/src/InspectorProxy.js:175:10)
    at Server.<anonymous> (/node_modules/metro/src/index.js:265:28)
    at Object.onceWrapper (node:events:509:28)
    at Server.emit (node:events:390:28)
    at emitListeningNT (node:net:1368:10)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)
```

Please help! Thanks in advance!

答:
This may happen for a few reasons:

You have run the app using react-native run-android or directly from Android Studio (or XCode). When running this command, if the Metro bundler server is not active, it will start it. Doing so, it open the default Terminal.app on Mac and appear in your recent app if not pinned. So if you run manually afterward yarn start the port will already be used.

You are trying to start a second Metro bundler on the same port.

Recommanded solution

Find the already running server on this port using

```<code>sudo lsof -i :8084
</code>```

Kill it

```<code>kill -9 <PID>
</code>```

Alternative

Change the Metro port.

```<code>react-native start --port 8088
</code>```

You'll need to access the developer menu on each app re-install to change the bundler location: localhost:8088 for example.

Body:
I'm trying to run yarn start, not working for me. I have tried changing port but it gives the same result.

┌──────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│  Running Metro Bundler on port 8084.                                         │
│                                                                              │
│  Keep Metro running while developing on any JS projects. Feel free to        │
│  close this tab and run your own Metro instance if you prefer.               │
│                                                                              │
│  https://github.com/facebook/react-native                                    │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

warning: the transform cache was reset.
master/node_modules/ws/lib/websocket-server.js:83
        throw new Error(
        ^

Error: The HTTP/S server is already being used by another WebSocket server
    at new WebSocketServer (/node_modules/ws/lib/websocket-server.js:83:15)
    at InspectorProxy._addDeviceConnectionHandler (/node_modules/metro-inspector-proxy/src/InspectorProxy.js:220:17)
    at InspectorProxy.addWebSocketListener (/node_modules/metro-inspector-proxy/src/InspectorProxy.js:175:10)
    at Server.<anonymous> (/node_modules/metro/src/index.js:265:28)
    at Object.onceWrapper (node:events:509:28)
    at Server.emit (node:events:390:28)
    at emitListeningNT (node:net:1368:10)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)

Please help! Thanks in advance!

Body:
This may happen for a few reasons:

You have run the app using react-native run-android or directly from Android Studio (or XCode). When running this command, if the Metro bundler server is not active, it will start it. Doing so, it open the default Terminal.app on Mac and appear in your recent app if not pinned. So if you run manually afterward yarn start the port will already be used.

You are trying to start a second Metro bundler on the same port.

Recommanded solution

Find the already running server on this port using

sudo lsof -i :8084

Kill it

kill -9 <PID>

Alternative

Change the Metro port.

react-native start --port 8088

You'll need to access the developer menu on each app re-install to change the bundler location: localhost:8088 for example.


问:
How to change text color of disabled MUI Text Field | MUI v5?
I want to alter the font colour of disabled MUI TextField.
It should be black so that it is visible.

Here is code

```<code>   <TextField
     fullWidth
     variant="standard"
      size="small"
     id="id"
     name="name"
     type="text"
     InputProps={{disableUnderline: true}}
     disabled={true}
    />

</code>```

I removed underline for standard text Field. Now I want text color black when it is disabled.

答:
Inspired by Madhuri's solution, you can also use the sx prop without importing styled:</p>
```<code>   <TextField
     fullWidth
     variant="standard"
     size="small"
     id="id"
     name="name"
     type="text"
     InputProps={{disableUnderline: true}}
     disabled={true}
     sx={{
       "& .MuiInputBase-input.Mui-disabled": {
         WebkitTextFillColor: "black",
       },
     }}
    />
</code>```

Body:
I want to alter the font colour of disabled MUI TextField.
It should be black so that it is visible.

Here is code

   <TextField
     fullWidth
     variant="standard"
      size="small"
     id="id"
     name="name"
     type="text"
     InputProps={{disableUnderline: true}}
     disabled={true}
    />

I removed underline for standard text Field. Now I want text color black when it is disabled.

Body:
Inspired by Madhuri's solution, you can also use the sx prop without importing styled:

   <TextField
     fullWidth
     variant="standard"
     size="small"
     id="id"
     name="name"
     type="text"
     InputProps={{disableUnderline: true}}
     disabled={true}
     sx={{
       "& .MuiInputBase-input.Mui-disabled": {
         WebkitTextFillColor: "black",
       },
     }}
    />


问:
Simple variadic template function can't instantinate
I'm aware that sizeof...(Args...) yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.

```<code>// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args ();          // Line 7
// template <>
constexpr size_t num_args ()
{
    return 0;
}

template <typename H, typename... T>
constexpr size_t num_args ()                                // Line 16
{
    return 1 + num_args <T...> (); // *HERE*
}

int main ()
{
    std :: cout << num_args <int, int, int> ();
}
</code>```

This errors at *HERE* with

```<code>No matching function call to ...
... candidate is template<class H, class ... T> size_t num_args()
</code>```

i.e. it's not seeing the base case which is defined first. Forward-declaring template<typename...T>num_args(); introduces ambiguity in overload resolution.

```<code>x.cpp:30:45: note: candidates are:
x.cpp:7:36: note: size_t num_args() [with Args = {int, float, char}, size_t = long unsigned int]
x.cpp:16:9: note: size_t num_args() [with H = int, T = {float, char}, size_t = long unsigned int]
</code>```

I am using gcc 4.6. How can I make this work?

Thanks.

答:
You didn’t declare a base case. You have a template-free overload of your num_args function but when calling a function num_args<T...>() this will never be found, for obvious reasons: it will always try to instantiate a function template.

You can however specialise your function template to perform the desired operation.

```<code>template <>
constexpr size_t num_args<>()
{
    return 0;
}
</code>```

However, this won’t work either since here you’re specialising a parameterless function template and such a template doesn’t exist: your other function template num_args always has at least one argument, H.

In order to really make this work you need partial specialisations, and these only exist for class templates. So this is what you need here.

```<code>template <typename T>
struct num_args_t;

template <>
struct num_args_t {
    static size_t const value = 0;
};

template <typename H, typename T...>
struct num_args_t {
    static size_t const value = num_args_t<T...>::value + 1;
};

template <typename T...>
constexpr size_t num_args() {
    return num_args_t<T...>::value;
}
</code>```

Body:
I'm aware that sizeof...(Args...) yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.

// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args ();          // Line 7
// template <>
constexpr size_t num_args ()
{
    return 0;
}

template <typename H, typename... T>
constexpr size_t num_args ()                                // Line 16
{
    return 1 + num_args <T...> (); // *HERE*
}

int main ()
{
    std :: cout << num_args <int, int, int> ();
}

This errors at *HERE* with

No matching function call to ...
... candidate is template<class H, class ... T> size_t num_args()

i.e. it's not seeing the base case which is defined first. Forward-declaring template<typename...T>num_args(); introduces ambiguity in overload resolution.

x.cpp:30:45: note: candidates are:
x.cpp:7:36: note: size_t num_args() [with Args = {int, float, char}, size_t = long unsigned int]
x.cpp:16:9: note: size_t num_args() [with H = int, T = {float, char}, size_t = long unsigned int]

I am using gcc 4.6. How can I make this work?

Thanks.

Body:
You didn’t declare a base case. You have a template-free overload of your num_args function but when calling a function num_args<T...>() this will never be found, for obvious reasons: it will always try to instantiate a function template.

You can however specialise your function template to perform the desired operation.

template <>
constexpr size_t num_args<>()
{
    return 0;
}

However, this won’t work either since here you’re specialising a parameterless function template and such a template doesn’t exist: your other function template num_args always has at least one argument, H.

In order to really make this work you need partial specialisations, and these only exist for class templates. So this is what you need here.

template <typename T>
struct num_args_t;

template <>
struct num_args_t {
    static size_t const value = 0;
};

template <typename H, typename T...>
struct num_args_t {
    static size_t const value = num_args_t<T...>::value + 1;
};

template <typename T...>
constexpr size_t num_args() {
    return num_args_t<T...>::value;
}


问:
Counter and call duration combination in flutter
```<code>int score = 0;
score += 1;
</code>```

I wish to add 1 (+= 1) to score when call duration reach 30 seconds just once and reset the score to 0 when call duration is less than 30 seconds.

```<code>Text('$score')
</code>```

and show it like this

```<code>import 'package:permission_handler/permission_handler.dart';
import 'package:call_log/call_log.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
</code>```

I have imported 3 packages above

```<code>void callLogs() async {
  Iterable<CallLogEntry> entries = await CallLog.get();
  for (var item in entries) {
    print(Duration());   <--- Use Duration & if statement to solve but duration not printing
   }
 }
</code>```

and code I wrote above is not working as I imagined to even start with. What changes can I make for adding and resetting score to work? Please help and thanks in advance

答:
Your code waits for this call to complete so it never runs anything under it:

```<code>Iterable<CallLogEntry> entries = await CallLog.get();
</code>```

You could use the StopWatch object to get the time:

```<code>void callLogs() async {

    Stopwatch stopwatch = new Stopwatch()..start();

    Iterable<CallLogEntry> entries = await CallLog.get();
    for (var item in entries) {
        var duration = stopwatch.elapsed;
        print('Duration $duration');
   }
 }
</code>```

And use setState() to set score:

```<code>setState(() { duration > 30 ? score += 1 : score = 0 });
</code>```

Body:
int score = 0;
score += 1;

I wish to add 1 (+= 1) to score when call duration reach 30 seconds just once and reset the score to 0 when call duration is less than 30 seconds.

Text('$score')

and show it like this

import 'package:permission_handler/permission_handler.dart';
import 'package:call_log/call_log.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

I have imported 3 packages above

void callLogs() async {
  Iterable<CallLogEntry> entries = await CallLog.get();
  for (var item in entries) {
    print(Duration());   <--- Use Duration & if statement to solve but duration not printing
   }
 }

and code I wrote above is not working as I imagined to even start with. What changes can I make for adding and resetting score to work? Please help and thanks in advance

Body:
Your code waits for this call to complete so it never runs anything under it:

Iterable<CallLogEntry> entries = await CallLog.get();

You could use the StopWatch object to get the time:

void callLogs() async {

    Stopwatch stopwatch = new Stopwatch()..start();

    Iterable<CallLogEntry> entries = await CallLog.get();
    for (var item in entries) {
        var duration = stopwatch.elapsed;
        print('Duration $duration');
   }
 }

And use setState() to set score:

setState(() { duration > 30 ? score += 1 : score = 0 });


问:
Calculate date differences with a loop or lapply?
This is a snapshot from my dataset. Here is my goal for the analysis.

I want to filter my dataset for the sic code

I want to calculate the difference between the two dates and put it into the dataset

```<code>sic | Announcement_date
---  -------------------
13  | 2018-09-11
19  | 2014-06-11
92  | 2011-10-14
131 | 2010-07-02
131 | 2011-02-16
131 | 2011-10-12
</code>```

So for this example, my expected output would be:

```<code>sic | Announcement_date  | Difference
---  -------------------  ------------
13  | 2018-09-11          NA
19  | 2014-06-11          NA
92  | 2011-10-14          NA
131 | 2010-07-02          NA
131 | 2011-02-16          229 days
131 | 2011-10-12          #etc...
</code>```

As I'm rather new in R I'm at a loss for how to achieve this. Can someone help me out?

Thank you so much for your support.

答:
Ensure that your dates are in POSIXct format, then you can use diff to get the difference between the dates. Just group_by(sic), and ensure that you tack an extra NA on to the start of each group, since there is nothing to compare the first entry to in the diff

library(dplyr)

df %>%
  mutate(Announcement_date = as.POSIXct(Announcement_date)) %>%
  group_by(sic) %>%
  mutate(difference = c(NA, diff(Announcement_date)))
#> # A tibble: 6 x 3
#> # Groups:   sic [4]
#>     sic Announcement_date   difference
#>   <int> <dttm>                   <dbl>
#> 1    13 2018-09-11 00:00:00         NA
#> 2    19 2014-06-11 00:00:00         NA
#> 3    92 2011-10-14 00:00:00         NA
#> 4   131 2010-07-02 00:00:00         NA
#> 5   131 2011-02-16 00:00:00        229
#> 6   131 2011-10-12 00:00:00        238
```
<hr />
<p><strong>Data</strong></p>
<pre class="lang-r prettyprint-override"><code>df <- structure(list(sic = c(13L, 19L, 92L, 131L, 131L, 131L),
               Announcement_date = c("2018-09-11",
"2014-06-11", "2011-10-14", "2010-07-02", "2011-02-16", "2011-10-12"
)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
This is a snapshot from my dataset. Here is my goal for the analysis.

I want to filter my dataset for the sic code

I want to calculate the difference between the two dates and put it into the dataset

sic | Announcement_date
---  -------------------
13  | 2018-09-11
19  | 2014-06-11
92  | 2011-10-14
131 | 2010-07-02
131 | 2011-02-16
131 | 2011-10-12

So for this example, my expected output would be:

sic | Announcement_date  | Difference
---  -------------------  ------------
13  | 2018-09-11          NA
19  | 2014-06-11          NA
92  | 2011-10-14          NA
131 | 2010-07-02          NA
131 | 2011-02-16          229 days
131 | 2011-10-12          #etc...

As I'm rather new in R I'm at a loss for how to achieve this. Can someone help me out?

Thank you so much for your support.

Body:
Ensure that your dates are in POSIXct format, then you can use diff to get the difference between the dates. Just group_by(sic), and ensure that you tack an extra NA on to the start of each group, since there is nothing to compare the first entry to in the diff

library(dplyr)

df %>%
  mutate(Announcement_date = as.POSIXct(Announcement_date)) %>%
  group_by(sic) %>%
  mutate(difference = c(NA, diff(Announcement_date)))
#> # A tibble: 6 x 3
#> # Groups:   sic [4]
#>     sic Announcement_date   difference
#>   <int> <dttm>                   <dbl>
#> 1    13 2018-09-11 00:00:00         NA
#> 2    19 2014-06-11 00:00:00         NA
#> 3    92 2011-10-14 00:00:00         NA
#> 4   131 2010-07-02 00:00:00         NA
#> 5   131 2011-02-16 00:00:00        229
#> 6   131 2011-10-12 00:00:00        238

Data

df <- structure(list(sic = c(13L, 19L, 92L, 131L, 131L, 131L),
               Announcement_date = c("2018-09-11",
"2014-06-11", "2011-10-14", "2010-07-02", "2011-02-16", "2011-10-12"
)), class = "data.frame", row.names = c(NA, -6L))

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
```<code>var ctr = getCtr();
</code>```

This calls getCtr(), which initializes i to 0, and stores a reference to the function

```<code>function() {
    console.log(++i)
}
</code>```

in ctr. Because that function was created in the scope of getCtr(), the variable i is still accessible in the scope of the function stored in ctr.

The first call to

```<code>ctr()
</code>```

executes console.log(++i) which has a preincrement on i, so it prints out 1. The second call executes the same code, with the same preincrement, and prints out 2.

DISCLAIMER: Not a javascript developer. Forgive me if I've made an error or used some unpreferred wording.

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
var ctr = getCtr();

This calls getCtr(), which initializes i to 0, and stores a reference to the function

function() {
    console.log(++i)
}

in ctr. Because that function was created in the scope of getCtr(), the variable i is still accessible in the scope of the function stored in ctr.

The first call to

ctr()

executes console.log(++i) which has a preincrement on i, so it prints out 1. The second call executes the same code, with the same preincrement, and prints out 2.

DISCLAIMER: Not a javascript developer. Forgive me if I've made an error or used some unpreferred wording.


问:
Deserialization of reference types without parameterless constructor is not supported
I have this API

 public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
        {
            AddDocumentStatus documentState = _documentService.AddDocument(documentRequestModel, DocumentType.OutgoingPosShipment);
            if (documentState.IsSuccess)
                return Ok();

            return BadRequest();
        }
```
<p>And this is my request model</p>
<pre class="lang-cs prettyprint-override"><code>    public class AddDocumentRequestModel
    {
        public AddDocumentRequestModel(int partnerId, List<ProductRequestModel> products)
        {
            PartnerId = partnerId;
            Products = products;
        }

        [Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        public int PartnerId { get; private set; }

        [Required, MustHaveOneElement(ErrorMessage = "At least one product is required")]
        public List<ProductRequestModel> Products { get; private set; }
    }
</code>```

so when I'm trying to hit the API with this body

{
        "partnerId": 101,
        "products": [{
            "productId": 100,
            "unitOfMeasureId": 102,
            "quantity":5
        }
     ]
}
```

this is the request:

System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel'

I don't need a parameterless constructor, because it doesn't read the body parameters. Is there any other way for deserialization?

答: Just in case someone have the same issue I had, I was using abstract class, once removed the abstract key word, it all worked just fine.

Body:
I have this API

 public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
        {
            AddDocumentStatus documentState = _documentService.AddDocument(documentRequestModel, DocumentType.OutgoingPosShipment);
            if (documentState.IsSuccess)
                return Ok();

            return BadRequest();
        }

And this is my request model

    public class AddDocumentRequestModel
    {
        public AddDocumentRequestModel(int partnerId, List<ProductRequestModel> products)
        {
            PartnerId = partnerId;
            Products = products;
        }

        [Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        public int PartnerId { get; private set; }

        [Required, MustHaveOneElement(ErrorMessage = "At least one product is required")]
        public List<ProductRequestModel> Products { get; private set; }
    }

so when I'm trying to hit the API with this body

{
        "partnerId": 101,
        "products": [{
            "productId": 100,
            "unitOfMeasureId": 102,
            "quantity":5
        }
     ]
}

this is the request:

System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel'

I don't need a parameterless constructor, because it doesn't read the body parameters. Is there any other way for deserialization?


问:
Open Group Policy Management Console (gpmc) for Another Domain
I am trying to open a gpmc for another domain. We have 2 AD Domains A and B. There are no trusts between them. My Computer is joined to Domain A and I want to open a gpmc for domain B.

For DSA (AD Users and Computers) this seems to be possible like this:

runas.exe /netonly /user:<Domain B>\<Domain B User> "mmc dsa.msc /domain=<Domain B>"

but when I try to run this for gpmc the following error comes up:

I probably do not have access to the logs of either domain.

答:
It's been a while, but with the help of a colleague we came to a solution. The GPMC has an option called trust detection (View -> Options -> General).

Once this options is disabled, the GPMC has to be closed so that this option is saved. If you then start the GPMC via

runas.exe /netonly /user:<Domain B>\<Domain B User> "mmc gpmc.msc /domain=<Domain B>"

the forest from domain B can be added and you can configure your GPOs as you normally would.


问:
Get window position & size with python -- OS/system agnostic
There are a number of topics (Get window position & size with python) that address how to get the position and size of a window on an individual OS basis.

Is there a way to do this that's system-agnostic?

答:
I am not sure about a system-agnostic way of handling it, but when ever I run into an issue related to system specific operations. I will insert a platform check.

```<code>from sys import platform
if platform == "linux":
    # linux
elif platform == "darwin":
    # OS X
elif platform == "windows":
    # Windows...
</code>```

From there I can write out the appropriate operations for what ever task I need to complete on each platform.

Body:
I am not sure about a system-agnostic way of handling it, but when ever I run into an issue related to system specific operations. I will insert a platform check.

from sys import platform
if platform == "linux":
    # linux
elif platform == "darwin":
    # OS X
elif platform == "windows":
    # Windows...

From there I can write out the appropriate operations for what ever task I need to complete on each platform.


问:
How to fix conversion errors in a switch statement?
conversion error float to int

```<code>public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (distance >= (float) 75.0) {
        switch (distance) {
            case 5.0:
                float f_5 = (float) (80.0 * 5.0 * perc);
                label_f_5_result.setText("Rs.80 * 5 * " + perc + "( risk factor % ) = " + f_5);
                label_apx_delv_fee_result.setText("Rs." + f_5);
        }
    }
}
</code>```

I'm retrieving a distance value (like 1.5, 5, 4.3 in kilometers) from a jSpinner in my GUI. I have already changed the jSpinner model to [Number]>>(float). However I keep getting an IDE error even after I cast the calculations to float type:

```<code>possible lossy conversion from float to int error
</code>```

I'm still a Java beginner and I couldn't find a solution. However, if I change distance from float to int the error disappears but I want float values because a distance won't be a roundup.

答:
As said in the comments you cannot switch on variables of type float. Have a look at the switch documentation. In particular the initial part goes:

Unlike if-then and if-then-else statements, the switch statement can
have a number of possible execution paths. A switch works with the
byte, short, char, and int primitive data types.

This is because the representation of float values is inaccurate by nature. If you are interested in knowing more about floating points and why this happens, have a look at this.

As for how you might solve your situation, yes, you should go for if-else statements. However keep in mind that you cannot use == for float comparison (see this for more info). Try something like this:

```<code>public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (Float.compare(distance, 5f) == 0) {
        // do something
    }
}
</code>```

Go here for Float.compare() documentation.

Body:
conversion error float to int

public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (distance >= (float) 75.0) {
        switch (distance) {
            case 5.0:
                float f_5 = (float) (80.0 * 5.0 * perc);
                label_f_5_result.setText("Rs.80 * 5 * " + perc + "( risk factor % ) = " + f_5);
                label_apx_delv_fee_result.setText("Rs." + f_5);
        }
    }
}

I'm retrieving a distance value (like 1.5, 5, 4.3 in kilometers) from a jSpinner in my GUI. I have already changed the jSpinner model to [Number]>>(float). However I keep getting an IDE error even after I cast the calculations to float type:

possible lossy conversion from float to int error

I'm still a Java beginner and I couldn't find a solution. However, if I change distance from float to int the error disappears but I want float values because a distance won't be a roundup.

Body:
As said in the comments you cannot switch on variables of type float. Have a look at the switch documentation. In particular the initial part goes:

Unlike if-then and if-then-else statements, the switch statement can
have a number of possible execution paths. A switch works with the
byte, short, char, and int primitive data types.

This is because the representation of float values is inaccurate by nature. If you are interested in knowing more about floating points and why this happens, have a look at this.

As for how you might solve your situation, yes, you should go for if-else statements. However keep in mind that you cannot use == for float comparison (see this for more info). Try something like this:

public void priceMaker(float perc) {
    float distance = (float) dist.getValue();
    if (Float.compare(distance, 5f) == 0) {
        // do something
    }
}

Go here for Float.compare() documentation.


问:
find max. leaf nodes of a binary tree
```<code>       50
     /    \
   25      75
  /  \     / \
 15  27   62  79

depth = 3
total nodes = 7
max leaf nodes = 4
</code>```
```<code>       50
     /    \
   25      75
  /  \     / \
 15  27   62  79
 _    _   _    _
 1    1   1    1  = 4

</code>```

in a case where the Tree is full this will find the total amount of leaf nodes, but if the tree is not full and only the depth of the tree is known how can i know the max. leaf nodes in that tree?

// if the tree is full
function total_leafs_nodes(node, level, mxlevel)
  {
      if (node == null) {
        return 1;
      }
      if (node.left == null && node.right == null)
          return 1;

      else if (level == mxlevel)
      {
          return 1;
      }
      return (total_leafs_nodes(node.left, level + 1, mxlevel)
      + total_leafs_nodes(node.right, level + 1, mxlevel));
  }
```

答:
If there is a max number of child nodes that every node can have, then you can apply the following :

Let d equal the depth, m the number of max child nodes per node, and n the number of possible nodes, then...

```<code>n = m ^ (d - 1)
</code>```

Title: find max. leaf nodes of a binary tree

Body:
       50
     /    \
   25      75
  /  \     / \
 15  27   62  79

depth = 3
total nodes = 7
max leaf nodes = 4

       50
     /    \
   25      75
  /  \     / \
 15  27   62  79
 _    _   _    _
 1    1   1    1  = 4

in a case where the Tree is full this will find the total amount of leaf nodes, but if the tree is not full and only the depth of the tree is known how can i know the max. leaf nodes in that tree?

// if the tree is full
function total_leafs_nodes(node, level, mxlevel)
  {
      if (node == null) {
        return 1;
      }
      if (node.left == null && node.right == null)
          return 1;

      else if (level == mxlevel)
      {
          return 1;
      }
      return (total_leafs_nodes(node.left, level + 1, mxlevel)
      + total_leafs_nodes(node.right, level + 1, mxlevel));
  }

Body:
If there is a max number of child nodes that every node can have, then you can apply the following :

Let d equal the depth, m the number of max child nodes per node, and n the number of possible nodes, then...

n = m ^ (d - 1)


问:
Incompatible type referencing and referenced column in Spring Data JPA
I want my IDs to be uuid and there should be Many-To-One relationship between Student and course. I am getting incompitable types referencing column and referenced column.

Student.java

```<code>package com.test.model;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name="student",schema="mydb")
public class Student {

    @Id
    @Type(type="uuid-char")
    @Column(name="student_id")
    private UUID studentId;

    @Column(name="name")
    private String sudentName;

    @ManyToOne
    @JoinColumn(name="course_id")
    private Course course;

    @Column(name="course_id",insertable = false,updatable = false,nullable = false)
    private UUID courseId;

}

</code>```

Course.java

```<code>package com.test.model;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name="course",schema="mydb")
public class Course {

    @Id
    @Type(type="uuid-char")
    @Column(name="id")
    private UUID id;

    @Column(name="courseName")
    private String courseName;

}
</code>```

Exception

```<code>Caused by: java.sql.SQLException: Referencing column 'course_id' and referenced column 'id' in foreign key constraint 'FKdfypyqt0stgfc0aij9kcxm99s' are incompatible.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    ... 33 common frames omitted
</code>```

答:
Please learn how to create associations

what is @JoinColumn and how it is used in Hibernate

Never use raw ids like courseId! You already have @ManyToOne association with @JoinColumn annotation. Hibernate is smart enough to understand that course_id will be used as a foreign key.

@Table(name="student",schema="mydb")
public class Student {

    @Id
    @Type(type="uuid-char")
    @Column(name="student_id")
    private UUID studentId;

    @Column(name="name")
    private String sudentName;

    @ManyToOne
    @JoinColumn(name="course_id")
    private Course course;

}
```

Body:
I want my IDs to be uuid and there should be Many-To-One relationship between Student and course. I am getting incompitable types referencing column and referenced column.

Student.java

package com.test.model;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name="student",schema="mydb")
public class Student {

    @Id
    @Type(type="uuid-char")
    @Column(name="student_id")
    private UUID studentId;

    @Column(name="name")
    private String sudentName;

    @ManyToOne
    @JoinColumn(name="course_id")
    private Course course;

    @Column(name="course_id",insertable = false,updatable = false,nullable = false)
    private UUID courseId;

}

Course.java

package com.test.model;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name="course",schema="mydb")
public class Course {

    @Id
    @Type(type="uuid-char")
    @Column(name="id")
    private UUID id;

    @Column(name="courseName")
    private String courseName;

}

Exception

Caused by: java.sql.SQLException: Referencing column 'course_id' and referenced column 'id' in foreign key constraint 'FKdfypyqt0stgfc0aij9kcxm99s' are incompatible.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.28.jar:8.0.28]
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    ... 33 common frames omitted


问:
Trouble parsing out shapefile by market using geopandas package
im trying to follow documentation from https://geopandas.org/en/stable/docs/user_guide/io.html to try to read subsets of a massive shapefile.

this is the code they give as an example to read in a subset of just data in Africa:

```<code>gdf_mask = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_lowres")
)
gdf = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_cities"),
    mask=gdf_mask[gdf_mask.continent=="Africa"],
)
</code>```

Now here is the code i used for my case:

```<code>newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')
newdf = geopandas.read_file('C:\\Users\\path\\to\\file.zip', mask=newdf_mask[newdf_mask.RMName = "Tampa/St. Petersburg"],)
</code>```

I received an invalid syntax error. I also tried it without that trailing comma which seems out of place but they have it in their example.

as you can see from my code, I want to read a subset of the shapefile where the RMName = "Tampa/St. Petersburg".

Is this the best way to do it or is there a better or easier way?

答:
as documentation said :

You can also load ZIP files that contain your data:
zipfile = "zip:///Users/name/Downloads/cb_2017_us_state_500k.zip"
states = geopandas.read_file(zipfile)

and you dont specified "zip:///" in your code.

```<code>newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')
</code>```

try that and if you recieve error, post error message

Body:
im trying to follow documentation from https://geopandas.org/en/stable/docs/user_guide/io.html to try to read subsets of a massive shapefile.

this is the code they give as an example to read in a subset of just data in Africa:

gdf_mask = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_lowres")
)
gdf = geopandas.read_file(
    geopandas.datasets.get_path("naturalearth_cities"),
    mask=gdf_mask[gdf_mask.continent=="Africa"],
)

Now here is the code i used for my case:

newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')
newdf = geopandas.read_file('C:\\Users\\path\\to\\file.zip', mask=newdf_mask[newdf_mask.RMName = "Tampa/St. Petersburg"],)

I received an invalid syntax error. I also tried it without that trailing comma which seems out of place but they have it in their example.

as you can see from my code, I want to read a subset of the shapefile where the RMName = "Tampa/St. Petersburg".

Is this the best way to do it or is there a better or easier way?

Body:
as documentation said :

You can also load ZIP files that contain your data:
zipfile = "zip:///Users/name/Downloads/cb_2017_us_state_500k.zip"
states = geopandas.read_file(zipfile)

and you dont specified "zip:///" in your code.

newdf_mask = geopandas.read_file('C:\\Users\\path\\to\\file.zip')

try that and if you recieve error, post error message


问:
optimizing memory intensive script
I currently have this code:

```<code>  shop_category.shop_sub_categories.each do |sub_category|
     products << sub_category.products
   end

   products = products.flatten.uniq.compact

   data = products.first(100).map do |product|
    {
      :name => CGI.unescapeHTML(product.name),
      :manufacturer => product.manufacturer,
      :detail => product.description,
      :sales_rank => product.sales_rank,
      :price => product.price,
      :retailer => product.retailer
    }
   end
</code>```

I have found this pretty much memory intensive as it uses up to 96% of my CPU:

```<code>   shop_category.shop_sub_categories.each do |sub_category|
     products << sub_category.products
   end
</code>```

I am thinking of making a writing something in tune of a WHERE IN statement so that I might only query data from like so:

SELECT * FROM products JOIN shop_categorization ON product_id = products.id WHERE shop_sub_category_id IN (1,2,3,4,5)

I currently put on this script which does great. I am thinking if there is something that can be done to make this more Rails-y.

```<code>  sub_category_ids = shop_category.shop_sub_categories.map(&:id)
  sub_category_ids = sub_category_ids.join(',')
  products = Product.find_by_sql("SELECT * FROM products JOIN shop_sub_categorizations ON product_id = products.id WHERE shop_sub_categorizations.shop_sub_category_id IN (#{sub_category_ids}) LIMIT 100")
</code>```

答:
If you just want the sub category ids, instead of:

```<code>  sub_category_ids = shop_category.shop_sub_categories.map(&:id)
</code>```

You can instead select just the id column:

```<code>  sub_category_ids = shop_category.shop_sub_categories.select('id').map(&:id)
</code>```

Additionally, to reconstruct your find_by_sql statement to work using the ActiveRecord methods you could do the following:

```<code>  products = Product.join("JOIN shop_sub_categorizations ON product_id = products.id").where(["shop_sub_categorizations.shop_sub_category_id IN (?)", sub_category_ids]).limit(100)
</code>```

Remember that by not specifying the columns to select you are increasing the computational overhead of selecting back all columns and mapping them into memory.

EDIT:

Look at a process monitor to determine if your overhead is the Ruby script, or the database. It is possible that adding indexes to the database will decrease the CPU overhead of the database query. More information on SQL indexes here: http://www.w3schools.com/sql/sql_create_index.asp

Title: optimizing memory intensive script

Body:
I currently have this code:

  shop_category.shop_sub_categories.each do |sub_category|
     products << sub_category.products
   end

   products = products.flatten.uniq.compact

   data = products.first(100).map do |product|
    {
      :name => CGI.unescapeHTML(product.name),
      :manufacturer => product.manufacturer,
      :detail => product.description,
      :sales_rank => product.sales_rank,
      :price => product.price,
      :retailer => product.retailer
    }
   end

I have found this pretty much memory intensive as it uses up to 96% of my CPU:

   shop_category.shop_sub_categories.each do |sub_category|
     products << sub_category.products
   end

I am thinking of making a writing something in tune of a WHERE IN statement so that I might only query data from like so:

SELECT * FROM products JOIN shop_categorization ON product_id = products.id WHERE shop_sub_category_id IN (1,2,3,4,5)

I currently put on this script which does great. I am thinking if there is something that can be done to make this more Rails-y.

  sub_category_ids = shop_category.shop_sub_categories.map(&:id)
  sub_category_ids = sub_category_ids.join(',')
  products = Product.find_by_sql("SELECT * FROM products JOIN shop_sub_categorizations ON product_id = products.id WHERE shop_sub_categorizations.shop_sub_category_id IN (#{sub_category_ids}) LIMIT 100")

Body:
If you just want the sub category ids, instead of:

  sub_category_ids = shop_category.shop_sub_categories.map(&:id)

You can instead select just the id column:

  sub_category_ids = shop_category.shop_sub_categories.select('id').map(&:id)

Additionally, to reconstruct your find_by_sql statement to work using the ActiveRecord methods you could do the following:

  products = Product.join("JOIN shop_sub_categorizations ON product_id = products.id").where(["shop_sub_categorizations.shop_sub_category_id IN (?)", sub_category_ids]).limit(100)

Remember that by not specifying the columns to select you are increasing the computational overhead of selecting back all columns and mapping them into memory.

EDIT:

Look at a process monitor to determine if your overhead is the Ruby script, or the database. It is possible that adding indexes to the database will decrease the CPU overhead of the database query. More information on SQL indexes here: http://www.w3schools.com/sql/sql_create_index.asp


问:
How to use isArray() in Angular 2+ template?
I have this variable named records,

Now I want to check if its an array or not in angular2/typescript?

In AngularJS I used to do Following:

```<code>ng-if="selectedCol.data && !isArray(selectedCol.data)"
</code>```

But When I am trying to do the Following its not working;

```<code>*ngIf="selectedCol.model.data && !Array.isArray(selectedCol.model.data)"
</code>```

Its giving me below error:

TypeError: Cannot read property 'isArray' of undefined
  any inputs?

答:
Angular way: https://angular.io/guide/pipes

is-array.pipe.ts

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'isArray' })
export class IsArrayPipe implements PipeTransform {
  transform(value: unknown): boolean {
      return Array.isArray(value);
  }
}
</code>```

my.component.html

```<code><div *ngIf="selectedCol.model.data | isArray">...</div>
</code>```

Body:
I have this variable named records,

Now I want to check if its an array or not in angular2/typescript?

In AngularJS I used to do Following:

ng-if="selectedCol.data && !isArray(selectedCol.data)"

But When I am trying to do the Following its not working;

*ngIf="selectedCol.model.data && !Array.isArray(selectedCol.model.data)"

Its giving me below error:

TypeError: Cannot read property 'isArray' of undefined
  any inputs?

Body:
Angular way: https://angular.io/guide/pipes

is-array.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'isArray' })
export class IsArrayPipe implements PipeTransform {
  transform(value: unknown): boolean {
      return Array.isArray(value);
  }
}

my.component.html

<div *ngIf="selectedCol.model.data | isArray">...</div>


问:
Highcharts: How to add another(custom) label/ legend/ something else to the top right of the graph?
In my highcharts, I already have a legend at the bottom left of the graph but want to add a custom status indicator for the entire graph. It's going to be a colored oval with a colored dot and a status on it like in the picture.

Should I be trying to use a custom legend or something else? I don't need to hide/show abiliity of the legend so maybe I'm thinking a label is more appropriate but it seems like those only go in the graph. I want something on the top right of the graph. I'm looking through the API to see what else is available but haven't found one that suites my needs.

edit-
seems like I might have to do "chart.renderer.text" but I'm not sure how to convert and make it work in typescript http://jsfiddle.net/phpdeveloperrahul/HW7Rm/

```<code>function (chart) {

var point = chart.series[0].data[8],
    text = chart.renderer.text(
        'Max',
        point.plotX + chart.plotLeft + 10,
        point.plotY + chart.plotTop - 10
    ).attr({
        zIndex: 5
    }).add(),
    box = text.getBBox();

chart.renderer.rect(box.x - 5, box.y - 5, box.width + 10, box.height + 10, 5)
    .attr({
        fill: '#FFFFEF',
        stroke: 'gray',
        'stroke-width': 1,
        zIndex: 4
    })
    .add();
</code>```

});

答:
The best way to add a custom element inside the legend is to use the legend.labelFormatter.

```<code>events: {
  render() {
    let chart = this,
      legendAttr = chart.legend.box.getBBox(),
      padding = 5;

    chart.plus = chart.renderer.text('| +', chart.legend.box.parentGroup.alignAttr.translateX + legendAttr.width + padding, chart.spacingBox.height + padding / 2).attr({
      cursor: 'pointer',
    }).css({
      fontSize: 20
    }).on(
      "click",
      function() {
        alert('plus was clicked')
      }
    ).add()
  }
}
</code>```

API References:
https://api.highcharts.com/highcharts/legend.labelFormatter,

Demo: https://jsfiddle.net/BlackLabel/yu7qm9jx/1/

Body:
In my highcharts, I already have a legend at the bottom left of the graph but want to add a custom status indicator for the entire graph. It's going to be a colored oval with a colored dot and a status on it like in the picture.

Should I be trying to use a custom legend or something else? I don't need to hide/show abiliity of the legend so maybe I'm thinking a label is more appropriate but it seems like those only go in the graph. I want something on the top right of the graph. I'm looking through the API to see what else is available but haven't found one that suites my needs.

edit-
seems like I might have to do "chart.renderer.text" but I'm not sure how to convert and make it work in typescript http://jsfiddle.net/phpdeveloperrahul/HW7Rm/

function (chart) {

var point = chart.series[0].data[8],
    text = chart.renderer.text(
        'Max',
        point.plotX + chart.plotLeft + 10,
        point.plotY + chart.plotTop - 10
    ).attr({
        zIndex: 5
    }).add(),
    box = text.getBBox();

chart.renderer.rect(box.x - 5, box.y - 5, box.width + 10, box.height + 10, 5)
    .attr({
        fill: '#FFFFEF',
        stroke: 'gray',
        'stroke-width': 1,
        zIndex: 4
    })
    .add();

});

Body:
The best way to add a custom element inside the legend is to use the legend.labelFormatter.

events: {
  render() {
    let chart = this,
      legendAttr = chart.legend.box.getBBox(),
      padding = 5;

    chart.plus = chart.renderer.text('| +', chart.legend.box.parentGroup.alignAttr.translateX + legendAttr.width + padding, chart.spacingBox.height + padding / 2).attr({
      cursor: 'pointer',
    }).css({
      fontSize: 20
    }).on(
      "click",
      function() {
        alert('plus was clicked')
      }
    ).add()
  }
}

API References:
https://api.highcharts.com/highcharts/legend.labelFormatter,

Demo: https://jsfiddle.net/BlackLabel/yu7qm9jx/1/