问:
How to fix this problem? Login if statement not working
This is my views.py

```<code>def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})
</code>```

And this is my login page:

```<code><div class="container">
<div class="jumbotron">
    <h2 class="text-dark"> Login </h2>
    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
        <label for="username"> Username </label>
        <input type="text" name="username" placeholder=" Write Your UserName Here"> <br></br>

        <label for="password"> Password </label>
        <input type="text" name="password" placeholder=" Write Your Password Here"> <br></br>

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>
</div>
</code>```

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

答:
Since default authenticate always validate for username and password with is_active status that's why authenticate always returns None if user is inactive. You can make your own CustomLoginBackend and check for username and password and return user object if username and password correct otherwise returns None and check if user is active or not in your views.py

```<code>from django.contrib.auth import get_user_model

class CustomLoginBackend(object):

    def authenticate(self, request, username, password):
        User = get_user_model()
        try:
            user = User.objects.using(db_name).get(username=username)
        except User.DoesNotExist:
            return None
        else:
            if password is not None:
                if  user.check_password(password):
                    return user
        return None
</code>```

Then in your login views.

```<code>from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account is Inactive.")
        else:
            return HttpResponse("Invalid User Credentials Provided!!!!")
    else:
        return render(request, "MyTestApp/login.html", {})
</code>```

And at last don't forgot to add AUTHENTICATION_BACKENDS in your settings.py as

```<code>AUTHENTICATION_BACKENDS = ['path_to_your.CustomLoginBackend ',]
</code>```

Body:
This is my views.py

def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})

And this is my login page:

 Login

    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
         Username
        <input type="text" name="username" placeholder=" Write Your UserName Here">

         Password
        <input type="text" name="password" placeholder=" Write Your Password Here">

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

Body:
Since default authenticate always validate for username and password with is_active status that's why authenticate always returns None if user is inactive. You can make your own CustomLoginBackend and check for username and password and return user object if username and password correct otherwise returns None and check if user is active or not in your views.py

from django.contrib.auth import get_user_model

class CustomLoginBackend(object):

    def authenticate(self, request, username, password):
        User = get_user_model()
        try:
            user = User.objects.using(db_name).get(username=username)
        except User.DoesNotExist:
            return None
        else:
            if password is not None:
                if  user.check_password(password):
                    return user
        return None

Then in your login views.

from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account is Inactive.")
        else:
            return HttpResponse("Invalid User Credentials Provided!!!!")
    else:
        return render(request, "MyTestApp/login.html", {})

And at last don't forgot to add AUTHENTICATION_BACKENDS in your settings.py as

AUTHENTICATION_BACKENDS = ['path_to_your.CustomLoginBackend ',]


来源: stackexchange

问:
Why I cant use atoi() function on a "string" instead of the char pointer in C++?
I tried the following code and it is giving me error.

```<code>int main() {
    string String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
/*
error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
     int num = atoi(String);
                          ^
mingw32-make.exe[1]: *** [Debug/main.cpp.o] Error 1
mingw32-make.exe: *** [All] Error 2
*/
</code>```

But if I use the following code it works perfectly fine.

```<code>int main() {
    char* String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235
</code>```

I know I can solve my problem using stoi() function.

```<code>int main() {
    string String = "1235";
    int num = stoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235
</code>```

I can solve my problem by using a char pointer instead of string. But I just want to know why this can't be done by placing string itself into atoi(). How does atoi() work internally?

I just wanna know how does atoi() function work in C++

答:
Because const char* and std::string are incompatible, the implicit conversion
cause error.

If you still want to use std:string:

```<code>int main() {
    string String = "1235";
    int num = atoi(String.c_str());
    cout << num << endl;
    return 0;
}
</code>```

see this ref.

ContentLicense: CC BY-SA 4.0

Body:
I tried the following code and it is giving me error.

int main() {
    string String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
/*
error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
     int num = atoi(String);
                          ^
mingw32-make.exe[1]: *** [Debug/main.cpp.o] Error 1
mingw32-make.exe: *** [All] Error 2
*/

But if I use the following code it works perfectly fine.

int main() {
    char* String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235

I know I can solve my problem using stoi() function.

int main() {
    string String = "1235";
    int num = stoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235

I can solve my problem by using a char pointer instead of string. But I just want to know why this can't be done by placing string itself into atoi(). How does atoi() work internally?

I just wanna know how does atoi() function work in C++

Body:
Because const char* and std::string are incompatible, the implicit conversion
cause error.

If you still want to use std:string:

int main() {
    string String = "1235";
    int num = atoi(String.c_str());
    cout << num << endl;
    return 0;
}

see this ref.


问:
Failed to export the service using GKE Multi-Cluster Service
I'm configuring the GKE Multi-Cluster Service according to document1 and document2 and inspired by the multi-cluster-serice-communication-in-gke tutorial.

Somehow I'm failing on the "Registering a Service for export"
on second cluster.

I'm using the following YAML file to export the ngnix-service on the first(fleet cluster)

```<code># export.yaml
kind: ServiceExport
apiVersion: net.gke.io/v1
metadata:
 namespace: multy-service-poc
 name: ngnix-service
</code>```

and it's exported well - accessible from the another cluster and ServiceExport's status on the first cluster is True

```<code>k describe serviceexport ngnix-service
Name:         ngnix-service
Namespace:    multy-service-poc
Labels:       <none>
Annotations:  <none>
API Version:  net.gke.io/v1
Kind:         ServiceExport
Metadata:
  Creation Timestamp:  2021-12-11T11:22:37Z
  Finalizers:
    serviceexport.net.gke.io
  Generation:  2
  Managed Fields:
    API Version:  net.gke.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:kubectl.kubernetes.io/last-applied-configuration:
    Manager:      kubectl-client-side-apply
    Operation:    Update
    Time:         2021-12-11T11:22:37Z
    API Version:  net.gke.io/v1alpha1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:finalizers:
          .:
          v:"serviceexport.net.gke.io":
      f:spec:
      f:status:
        .:
        f:conditions:
    Manager:         Google-GKE-MCS
    Operation:       Update
    Time:            2021-12-11T11:22:39Z
  Resource Version:  58873
  UID:               a42dc51c-93ff-4526-9c04-9702ed7ba95d
Spec:
Status:
  Conditions:
    Last Transition Time:  2021-12-11T11:22:38Z
    Status:                True
    Type:                  Initialized
    Last Transition Time:  2021-12-11T11:22:40Z
    Status:                True
    Type:                  Exported
Events:                    <none>

</code>```

When I'm exporting the same service on the second cluster using same YAML file, it's failed and the status is False

```<code>kubectl  describe serviceexport ngnix-service
Name:         ngnix-service
Namespace:    multy-service-poc
Labels:       <none>
Annotations:  <none>
API Version:  net.gke.io/v1
Kind:         ServiceExport
Metadata:
  Creation Timestamp:  2021-12-13T07:29:36Z
  Finalizers:
    serviceexport.net.gke.io
  Generation:  2
  Managed Fields:
    API Version:  net.gke.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:kubectl.kubernetes.io/last-applied-configuration:
    Manager:      kubectl-client-side-apply
    Operation:    Update
    Time:         2021-12-13T07:29:36Z
    API Version:  net.gke.io/v1alpha1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:finalizers:
          .:
          v:"serviceexport.net.gke.io":
      f:spec:
      f:status:
        .:
        f:conditions:
    Manager:         Google-GKE-MCS
    Operation:       Update
    Time:            2021-12-13T07:31:10Z
  Resource Version:  1191220
  UID:               45bb42a8-effc-4a9d-95e8-22ff736a54af
Spec:
Status:
  Conditions:
    Last Transition Time:  2021-12-13T07:30:03Z
    Status:                True
    Type:                  Initialized
    Last Transition Time:  2021-12-13T07:31:10Z
    Message:               Conflicting "Project". Using from oldest service export in cluster "projects/mssp-eugene-mcs1/locations/us-east1/clusters/mssp-eugene-mcs-k8s-cluster1"
    Reason:                Conflict
    Status:                False
    Type:                  Exported
Events:                    <none>
</code>```

I see the clusters in the hub membership as well:

```<code>gcloud container hub memberships list --project eugene-mcs1
NAME                          EXTERNAL_ID
eugene-mcs-k8s-cluster2  e943ed80-6a49-4781-897c-57ae3266fb37
eugene-mcs-k8s-cluster1  074d59f2-fce2-491e-a99e-6d2b8587803c
</code>```

Expected behavior is ngnix-service exported from both clusters and exposes the ngnix pods from both clusters accordingly.

My configuration is
2 K8S clusters in the different projects using Shared VPC from the third host project.

Thanks

答:
Actually, the GKE Multi-Cluster Service works only for cluster within the same host project even the documentation told that it works for the clusters in the different projects.

This is an official response to my ticket from the Google Cloud Support:

I have received the following feedback from the Google product engineering team:

...
As there are one Host project, one fleet service project 1, and one service project 2 ,any given service’s backends must be entirely contained within a single project ;in other words, backends will only aggregate from clusters within a single project, though they can be from multiple clusters in that service project 1 (which still allows for fault tolerance as those clusters can be from different regions, just not across a project boundary). Those backends via the VPC Shared MCS service (i.e. yourservice.yournamespace.svc.clusterset.local), the service project 2 can be reachable to the backends in service project 1 using MCS as long as they have the namespace (i.e. yournamespace) present.

Therefore, your target service, all backing pods (and therefore all ServiceExports) should be in clusters in VPC service project 1. For fault tolerance, there should be several clusters in VPC service project 1 exporting this Service that are from different regions. That service may be in clusters in VPC service project 2 as the VPC service project 1 backends ...

As discussed above,  the high availability of services with MCS using the clusters from different Shared VPC service projects (not the clusters in different regions ) is unfortunately currently not possible. This is because the MCS workload cannot yet resolve common exported services with different project IDs. I hope my explanation is clear, if there is anything that you don’t understand, please let me know.

If you want I can  create a Public Issue Tracker to request this feature so you may follow any updates around this issue. However, I am unable to provide an estimated time of when this would be implemented if at all.

Body:
I'm configuring the GKE Multi-Cluster Service according to document1 and document2 and inspired by the multi-cluster-serice-communication-in-gke tutorial.

Somehow I'm failing on the "Registering a Service for export"
on second cluster.

I'm using the following YAML file to export the ngnix-service on the first(fleet cluster)

# export.yaml
kind: ServiceExport
apiVersion: net.gke.io/v1
metadata:
 namespace: multy-service-poc
 name: ngnix-service

and it's exported well - accessible from the another cluster and ServiceExport's status on the first cluster is True

k describe serviceexport ngnix-service
Name:         ngnix-service
Namespace:    multy-service-poc
Labels:       <none>
Annotations:  <none>
API Version:  net.gke.io/v1
Kind:         ServiceExport
Metadata:
  Creation Timestamp:  2021-12-11T11:22:37Z
  Finalizers:
    serviceexport.net.gke.io
  Generation:  2
  Managed Fields:
    API Version:  net.gke.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:kubectl.kubernetes.io/last-applied-configuration:
    Manager:      kubectl-client-side-apply
    Operation:    Update
    Time:         2021-12-11T11:22:37Z
    API Version:  net.gke.io/v1alpha1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:finalizers:
          .:
          v:"serviceexport.net.gke.io":
      f:spec:
      f:status:
        .:
        f:conditions:
    Manager:         Google-GKE-MCS
    Operation:       Update
    Time:            2021-12-11T11:22:39Z
  Resource Version:  58873
  UID:               a42dc51c-93ff-4526-9c04-9702ed7ba95d
Spec:
Status:
  Conditions:
    Last Transition Time:  2021-12-11T11:22:38Z
    Status:                True
    Type:                  Initialized
    Last Transition Time:  2021-12-11T11:22:40Z
    Status:                True
    Type:                  Exported
Events:                    <none>

When I'm exporting the same service on the second cluster using same YAML file, it's failed and the status is False

kubectl  describe serviceexport ngnix-service
Name:         ngnix-service
Namespace:    multy-service-poc
Labels:       <none>
Annotations:  <none>
API Version:  net.gke.io/v1
Kind:         ServiceExport
Metadata:
  Creation Timestamp:  2021-12-13T07:29:36Z
  Finalizers:
    serviceexport.net.gke.io
  Generation:  2
  Managed Fields:
    API Version:  net.gke.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:kubectl.kubernetes.io/last-applied-configuration:
    Manager:      kubectl-client-side-apply
    Operation:    Update
    Time:         2021-12-13T07:29:36Z
    API Version:  net.gke.io/v1alpha1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:finalizers:
          .:
          v:"serviceexport.net.gke.io":
      f:spec:
      f:status:
        .:
        f:conditions:
    Manager:         Google-GKE-MCS
    Operation:       Update
    Time:            2021-12-13T07:31:10Z
  Resource Version:  1191220
  UID:               45bb42a8-effc-4a9d-95e8-22ff736a54af
Spec:
Status:
  Conditions:
    Last Transition Time:  2021-12-13T07:30:03Z
    Status:                True
    Type:                  Initialized
    Last Transition Time:  2021-12-13T07:31:10Z
    Message:               Conflicting "Project". Using from oldest service export in cluster "projects/mssp-eugene-mcs1/locations/us-east1/clusters/mssp-eugene-mcs-k8s-cluster1"
    Reason:                Conflict
    Status:                False
    Type:                  Exported
Events:                    <none>

I see the clusters in the hub membership as well:

gcloud container hub memberships list --project eugene-mcs1
NAME                          EXTERNAL_ID
eugene-mcs-k8s-cluster2  e943ed80-6a49-4781-897c-57ae3266fb37
eugene-mcs-k8s-cluster1  074d59f2-fce2-491e-a99e-6d2b8587803c

Expected behavior is ngnix-service exported from both clusters and exposes the ngnix pods from both clusters accordingly.

My configuration is
2 K8S clusters in the different projects using Shared VPC from the third host project.

Thanks


问:
Why err when me export class?
I have built models NodeJs. But I don't understand why the error at the moment:

export default Products = mongoose.model("Products", productSchema);
^

ReferenceError: Products is not defined

```<code>import mongoose from "mongoose";

const productSchema = mongoose.Schema({
    name: String,
    price: Number,
    image: String,
    discount: {
      type: Number,
      require: false,
    },
  });

export default Products = mongoose.model("Products", productSchema);
</code>```

答:
You can't have a named default export. You would have to write it like so:

export default mongoose.model("Products", productSchema);
```

Title: Why err when me export class?

Body:
I have built models NodeJs. But I don't understand why the error at the moment:

export default Products = mongoose.model("Products", productSchema);
^

ReferenceError: Products is not defined

import mongoose from "mongoose";

const productSchema = mongoose.Schema({
    name: String,
    price: Number,
    image: String,
    discount: {
      type: Number,
      require: false,
    },
  });

export default Products = mongoose.model("Products", productSchema);


问:
How to handle the more than two images in the tableview?
Iam developing one application.In that i use the 4 rows for table view.Each row contain the imageview.Every imageview canget the image from CAMERA.My problem is after getting the third image,images will be appear at different positions.ANd if u scroll the tableviewthen imageviews will got the black color.Images not appeared.Please tell me how to solve this one.Is this memory problem or not.please tell me.</p>

答:
Check out this,</p>

```<code>    UIImageView *backgroundCellImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 80)];
        backgroundCellImage.image=[UIImage imageNamed:@"ImageName1.png"];

UIImageView *separatorImage=[[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 62, 80)];
separatorImage.image=[UIImage imageNamed:@"ImageName2.png"];

    [cell.contentView addSubview:backgroundCellImage];
            [cell.contentView addSubview:separatorImage];
            [backgroundCellImage release];
            [separatorImage release];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Check out this,

    UIImageView *backgroundCellImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 80)];
        backgroundCellImage.image=[UIImage imageNamed:@"ImageName1.png"];

UIImageView *separatorImage=[[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 62, 80)];
separatorImage.image=[UIImage imageNamed:@"ImageName2.png"];

    [cell.contentView addSubview:backgroundCellImage];
            [cell.contentView addSubview:separatorImage];
            [backgroundCellImage release];
            [separatorImage release];


问:
Module 'firebase_analytics' not found when archiving ios(Flutter app)
I have been trying to archive my ios app for days but i keep getting this error. When i run in debug mode though, it builds successfully.
I've done these repeatedly but still no hope:

Adding GoogleService-info.plist via xcode

Flutter clean

Deleted podfile, podfile.lock, symlinks

Flutter pub get

pod install &&pod repo update

Launch Runner.xcworkspace in xcode

My podfile

```<code>
platform :ios, '11.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

</code>```

Firebase packages im using

```<code>  firebase_core: ^0.5.3
  firebase_analytics: ^6.3.0
  firebase_messaging: ^7.0.3
  firebase_dynamic_links: ^0.6.3
</code>```

答:
I also faced the same issue, here's what worked for me:

Add this in Pod file

```<code>target 'Runner' do
 pod 'Firebase/Analytics'
end
</code>```

Body:
I have been trying to archive my ios app for days but i keep getting this error. When i run in debug mode though, it builds successfully.
I've done these repeatedly but still no hope:

Adding GoogleService-info.plist via xcode

Flutter clean

Deleted podfile, podfile.lock, symlinks

Flutter pub get

pod install &&pod repo update

Launch Runner.xcworkspace in xcode

My podfile

platform :ios, '11.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

Firebase packages im using

  firebase_core: ^0.5.3
  firebase_analytics: ^6.3.0
  firebase_messaging: ^7.0.3
  firebase_dynamic_links: ^0.6.3

Body:
I also faced the same issue, here's what worked for me:

Add this in Pod file

target 'Runner' do
 pod 'Firebase/Analytics'
end


问:
pandas finding duplicate rows with different label
I have the case where I want to sanity check labeled data. I have hundreds of features and want to find points which have the same features but different label. These found cluster of disagreeing labels should then be numbered and put into a new dataframe.
This isn't hard but I am wondering what the most elegant solution for this is.
Here an example:</p>
```<code>import pandas as pd

df = pd.DataFrame({
    "feature_1" : [0,0,0,4,4,2],
    "feature_2" : [0,5,5,1,1,3],
    "label" : ["A","A","B","B","D","A"]
})

result_df = pd.DataFrame({
    "cluster_index" : [0,0,1,1],
    "feature_1" : [0,0,4,4],
    "feature_2" : [5,5,1,1],
    "label" : ["A","B","B","D"]
})
</code>```

答:
In order to get the output you want (both de-duplication and cluster_index), you can use a groupby approach:

```<code>g = df.groupby(['feature_1', 'feature_2'])['label']

(df.assign(cluster_index=g.ngroup()) # get group name
   .loc[g.transform('size').gt(1)]   # filter the non-duplicates
   # line below only to have a nice cluster_index range (0,1…)
   .assign(cluster_index= lambda d: d['cluster_index'].factorize()[0])
)
</code>```

output:

```<code>   feature_1  feature_2 label  cluster_index
1          0          5     A              0
2          0          5     B              0
3          4          1     B              1
4          4          1     D              1
</code>```

Body:
I have the case where I want to sanity check labeled data. I have hundreds of features and want to find points which have the same features but different label. These found cluster of disagreeing labels should then be numbered and put into a new dataframe.
This isn't hard but I am wondering what the most elegant solution for this is.
Here an example:

import pandas as pd

df = pd.DataFrame({
    "feature_1" : [0,0,0,4,4,2],
    "feature_2" : [0,5,5,1,1,3],
    "label" : ["A","A","B","B","D","A"]
})

result_df = pd.DataFrame({
    "cluster_index" : [0,0,1,1],
    "feature_1" : [0,0,4,4],
    "feature_2" : [5,5,1,1],
    "label" : ["A","B","B","D"]
})

Body:
In order to get the output you want (both de-duplication and cluster_index), you can use a groupby approach:

g = df.groupby(['feature_1', 'feature_2'])['label']

(df.assign(cluster_index=g.ngroup()) # get group name
   .loc[g.transform('size').gt(1)]   # filter the non-duplicates
   # line below only to have a nice cluster_index range (0,1…)
   .assign(cluster_index= lambda d: d['cluster_index'].factorize()[0])
)

output:

   feature_1  feature_2 label  cluster_index
1          0          5     A              0
2          0          5     B              0
3          4          1     B              1
4          4          1     D              1


问:
How to use aggregate combinators ForEach + If
In ClickHouse I can change the way aggregation works with combinators.

the ForEach combinator aggregates the results over each element in an array:

```<code>SELECT avgForEach(array)
FROM test
</code>```

The If combinator can be used to perform conditional aggregation:

```<code>SELECT avgIf(col, col > 0)
FROM test
</code>```

But how can I use them in combination with each other to check whether each array element matches some condition before aggregating the value?

I tried using lambda functions as the conditional, but that didn't work e.g.:

```<code>SELECT avgForEachIf(array, x -> x > 0)
FROM test
</code>```

答:
For completeness sake, a coworker pointed out I was using the ForEach and If combinators in the wrong order. If you prepend the If it will evaluate on each array element. If you append the If it will evaluate the array as a whole.

Using that, you can create an array with boolean values indicating whether each element matches a condition with the IfForEach combinator:

```<code>WITH arrayJoin([[1, 1], [-1, 2]]) AS A
SELECT avgIfForEach(A, arrayMap(x -> (x > 0), A))

┌─avgIfForEach(A, arrayMap(lambda(tuple(x), greater(x, 0)), A))─┐
│ [1,1.5]                                                       │
└───────────────────────────────────────────────────────────────┘
</code>```

Body:
In ClickHouse I can change the way aggregation works with combinators.

the ForEach combinator aggregates the results over each element in an array:

SELECT avgForEach(array)
FROM test

The If combinator can be used to perform conditional aggregation:

SELECT avgIf(col, col > 0)
FROM test

But how can I use them in combination with each other to check whether each array element matches some condition before aggregating the value?

I tried using lambda functions as the conditional, but that didn't work e.g.:

SELECT avgForEachIf(array, x -> x > 0)
FROM test

Body:
For completeness sake, a coworker pointed out I was using the ForEach and If combinators in the wrong order. If you prepend the If it will evaluate on each array element. If you append the If it will evaluate the array as a whole.

Using that, you can create an array with boolean values indicating whether each element matches a condition with the IfForEach combinator:

WITH arrayJoin([[1, 1], [-1, 2]]) AS A
SELECT avgIfForEach(A, arrayMap(x -> (x > 0), A))

┌─avgIfForEach(A, arrayMap(lambda(tuple(x), greater(x, 0)), A))─┐
│ [1,1.5]                                                       │
└───────────────────────────────────────────────────────────────┘


问:
When changing from express to nginx
I'm a node js newbie and I'm looking for various materials now

When changing from express to nginx

Does it matter if the backend code inside doesn't change?

Things like nginx or apache don't seem to have anything to do with the backend code, so I'm asking just in case.

```<code>  app.get(
    "/hi",
    function (req, res, next) {
      res.send("hi");
    },
  );
</code>```

In the examples that did not use nginx, the code structure inside was almost like this. If you use nginx, nothing special will change in the backend code, right?

答:
You are describing a Reverse Proxy Use case. Short answer is in 90% of the cases NO - you don't have to change anything at your nodejs code.

A simple configuration could look like this:

Client -- req TCP 80 -> NGINX -- req TCP 3000 -> NODEJS EXPRESS | app.js
```
<p>The configuration</p>
```
upstream node_backend {
  server 127.0.0.1:3000;
  keepalive 32;
}

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://node_backend/;
    proxy_set_header Host $host;
    ...
  }
}
```

Notes:

Make sure you are managing the NodeApp in a proper way. Means how to start and stop it on system startup or something like that.

You would likely need HTTPS on the NGINX Side. This will not change the location configuration or the proxy_pass statement.

Title: When changing from express to nginx

Body:
I'm a node js newbie and I'm looking for various materials now

When changing from express to nginx

Does it matter if the backend code inside doesn't change?

Things like nginx or apache don't seem to have anything to do with the backend code, so I'm asking just in case.

  app.get(
    "/hi",
    function (req, res, next) {
      res.send("hi");
    },
  );

In the examples that did not use nginx, the code structure inside was almost like this. If you use nginx, nothing special will change in the backend code, right?

Body:
You are describing a Reverse Proxy Use case. Short answer is in 90% of the cases NO - you don't have to change anything at your nodejs code.

A simple configuration could look like this:

Client -- req TCP 80 -> NGINX -- req TCP 3000 -> NODEJS EXPRESS | app.js

The configuration

upstream node_backend {
  server 127.0.0.1:3000;
  keepalive 32;
}

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://node_backend/;
    proxy_set_header Host $host;
    ...
  }
}

Notes:

Make sure you are managing the NodeApp in a proper way. Means how to start and stop it on system startup or something like that.

You would likely need HTTPS on the NGINX Side. This will not change the location configuration or the proxy_pass statement.


问:
How to get deterministic behavior in Tensorflow
I have a very basic model training on MNIST, and I'd like to make the training process deterministic.

I've set all of these seeds mentioned in other posts:

```<code>import tensorflow as tf
import numpy as np
import random

tf.random.set_seed(12)
np.random.seed(12)
random.seed(12)

initializer = tf.keras.initializers.glorot_uniform(seed=12)
</code>```

And my model is the following:

```<code>model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu', kernel_initializer=initializer, bias_initializer=tf.keras.initializers.Zeros()),
  tf.keras.layers.Dense(10, kernel_initializer=initializer, bias_initializer=tf.keras.initializers.Zeros())
])
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)
</code>```

But I still see non-deterministic behavior from

```<code>model.fit(
    ds_train,
    epochs=2,
    validation_data=ds_test,
    callbacks=[callback],
    shuffle=False, use_multiprocessing=False
)
</code>```

Would appreciate any help with this! Thanks.

答:
There is no error, when I replicated these same codes with MNIST dataset in Google Colab with Tensorflow ==2.7.

```<code>model.fit(
    x_train, y_train,
    epochs=2,
    validation_data=(x_test, y_test),
    #callbacks=[callback],
    shuffle=False, use_multiprocessing=False
)
</code>```

Output:

```<code>Epoch 1/2
1875/1875 [==============================] - 13s 6ms/step - loss: 0.2687 - sparse_categorical_accuracy: 0.9232 - val_loss: 0.1686 - val_sparse_categorical_accuracy: 0.9460
Epoch 2/2
1875/1875 [==============================] - 10s 5ms/step - loss: 0.1215 - sparse_categorical_accuracy: 0.9646 - val_loss: 0.1375 - val_sparse_categorical_accuracy: 0.9561
<keras.callbacks.History at 0x7f51a89480d0>
</code>```

Let us know the traceback error you are getting and which Tensorflow are you using to be specific for replicating and fix this issue.

Body:
I have a very basic model training on MNIST, and I'd like to make the training process deterministic.

I've set all of these seeds mentioned in other posts:

import tensorflow as tf
import numpy as np
import random

tf.random.set_seed(12)
np.random.seed(12)
random.seed(12)

initializer = tf.keras.initializers.glorot_uniform(seed=12)

And my model is the following:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu', kernel_initializer=initializer, bias_initializer=tf.keras.initializers.Zeros()),
  tf.keras.layers.Dense(10, kernel_initializer=initializer, bias_initializer=tf.keras.initializers.Zeros())
])
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)

But I still see non-deterministic behavior from

model.fit(
    ds_train,
    epochs=2,
    validation_data=ds_test,
    callbacks=[callback],
    shuffle=False, use_multiprocessing=False
)

Would appreciate any help with this! Thanks.

Body:
There is no error, when I replicated these same codes with MNIST dataset in Google Colab with Tensorflow ==2.7.

model.fit(
    x_train, y_train,
    epochs=2,
    validation_data=(x_test, y_test),
    #callbacks=[callback],
    shuffle=False, use_multiprocessing=False
)

Output:

Epoch 1/2
1875/1875 [==============================] - 13s 6ms/step - loss: 0.2687 - sparse_categorical_accuracy: 0.9232 - val_loss: 0.1686 - val_sparse_categorical_accuracy: 0.9460
Epoch 2/2
1875/1875 [==============================] - 10s 5ms/step - loss: 0.1215 - sparse_categorical_accuracy: 0.9646 - val_loss: 0.1375 - val_sparse_categorical_accuracy: 0.9561
<keras.callbacks.History at 0x7f51a89480d0>

Let us know the traceback error you are getting and which Tensorflow are you using to be specific for replicating and fix this issue.


问:
How to make parser decide on which alternative to use, based on the rule in the previous step
I'm using ANTLR 4 to parse a protocol's messages, let's name it 'X'. Before extracting a message's information , I have to check if it complies with X's rules.

Suppose we have to parse X's 'FOO' message that follows the following rules:

Message starts with the 'messageIdentifier' that consists of the 3-letter reserved word FOO.

Message contains 5 fields, of which the first 2 are mandatory (must be included) and the rest 3 are optional (can be not included).

Message's fields are separated by the character '/'. If there is no information in a field (that means that the field is optional and is omitted) the '/' character must be preserved. Optional fields and their associated filed separators '/' at the end of the message may be omitted where no further information within the message is reported.

A message can expand in multiple lines. Each line must have at least one non-empty field (mandatory or optional). Moreover, each line must start with a '/' character and end with a non-empty field following a '\n' character. Exception is the first line that always starts with the reserved word FOO.

Each message's field also has its own rules regarding the accepted tokens, which will be shown in the grammar below.

Sample examples of valid FOO messages:

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2\n

/OPT 1\n

/HELLO\n

/100\n

FOO/MANDATORY_1/MANDATORY2\n

FOO/MANDATORY_1/MANDATORY2//HELLO/100\n

FOO/MANDATORY_1/MANDATORY2///100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1\n

FOO/MANDATORY_1/MANDATORY2
///100\n

Sample examples of non-valid FOO messages:

FOO\n

/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/\n

MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1//\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/\n

/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100

Below follows the grammar for the above message:

```<code>grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? optionalField_3 ;

optionalField_3 : '/' field_3 NL? optionalField_4
                | '/' optionalField_4
                | optionalField_4
                ;

optionalField_4 : '/' field_4 NL? optionalField_5
                | '/' optionalField_5
                | optionalField_5
                ;

optionalField_5 : '/' field_5 NL?
                | NL
                ;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;

</code>```

The above grammar parses correctly any input that complies with FOO message's rules.
The problem resides in parsing a line that ends with the '/' character, which according to the protocol's FOO message's rules is an invalid input.
I understand that the second alternatives of rules 'optionalField_3', 'optionalField_4' and 'optionalField_5' lead to this behavior but I can't figure out how to make a rule for this.
Somehow I need the parser to remember that he came to 'optionalField_5' rule after seeing a non-omitted field in the previous rule, which if I am not mistaken can't be done in ANTLR as I can't check from which alternative of the previous rule I reached the current rule.

Is there a way to make the parser 'remember' this by some explicit option-rule? Or does my grammar need to be rearranged and if yes how?

答:
Solution was to refactor my grammar to include rules for filledField and emptyField.

kaby76's post is marked as an answer as it helped towards the solution.

The refactored grammar:

```<code>grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 endRule ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? (filledOptionalField_3 | emptyOptionalField_3 )? ;

filledOptionalField_3 : '/' field_3 NL? (filledOptionalField_4 | emptyOptionalField_4)? ;
emptyOptionalField_3 : '/' (filledOptionalField_4 | emptyOptionalField_4) ;

filledOptionalField_4 : '/' field_4 NL? filledOptionalField_5? ;
emptyOptionalField_4 : '/' filledOptionalField_5 ;

filledOptionalField_5 : '/' field_5 ;

endRule : NL;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;

</code>```

Body:
I'm using ANTLR 4 to parse a protocol's messages, let's name it 'X'. Before extracting a message's information , I have to check if it complies with X's rules.

Suppose we have to parse X's 'FOO' message that follows the following rules:

Message starts with the 'messageIdentifier' that consists of the 3-letter reserved word FOO.

Message contains 5 fields, of which the first 2 are mandatory (must be included) and the rest 3 are optional (can be not included).

Message's fields are separated by the character '/'. If there is no information in a field (that means that the field is optional and is omitted) the '/' character must be preserved. Optional fields and their associated filed separators '/' at the end of the message may be omitted where no further information within the message is reported.

A message can expand in multiple lines. Each line must have at least one non-empty field (mandatory or optional). Moreover, each line must start with a '/' character and end with a non-empty field following a '\n' character. Exception is the first line that always starts with the reserved word FOO.

Each message's field also has its own rules regarding the accepted tokens, which will be shown in the grammar below.

Sample examples of valid FOO messages:

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2\n

/OPT 1\n

/HELLO\n

/100\n

FOO/MANDATORY_1/MANDATORY2\n

FOO/MANDATORY_1/MANDATORY2//HELLO/100\n

FOO/MANDATORY_1/MANDATORY2///100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1\n

FOO/MANDATORY_1/MANDATORY2
///100\n

Sample examples of non-valid FOO messages:

FOO\n

/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/\n

MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1//\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/\n

/100\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100\n

FOO/MANDATORY_1/MANDATORY2/\n

FOO/MANDATORY_1/MANDATORY2/OPT 1/HELLO/100

Below follows the grammar for the above message:

grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? optionalField_3 ;

optionalField_3 : '/' field_3 NL? optionalField_4
                | '/' optionalField_4
                | optionalField_4
                ;

optionalField_4 : '/' field_4 NL? optionalField_5
                | '/' optionalField_5
                | optionalField_5
                ;

optionalField_5 : '/' field_5 NL?
                | NL
                ;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;

The above grammar parses correctly any input that complies with FOO message's rules.
The problem resides in parsing a line that ends with the '/' character, which according to the protocol's FOO message's rules is an invalid input.
I understand that the second alternatives of rules 'optionalField_3', 'optionalField_4' and 'optionalField_5' lead to this behavior but I can't figure out how to make a rule for this.
Somehow I need the parser to remember that he came to 'optionalField_5' rule after seeing a non-omitted field in the previous rule, which if I am not mistaken can't be done in ANTLR as I can't check from which alternative of the previous rule I reached the current rule.

Is there a way to make the parser 'remember' this by some explicit option-rule? Or does my grammar need to be rearranged and if yes how?

Body:
Solution was to refactor my grammar to include rules for filledField and emptyField.

kaby76's post is marked as an answer as it helped towards the solution.

The refactored grammar:

grammar Foo_Message

/* Parser Rules */

startRule : 'FOO' mandatoryField_1 endRule ;

mandatoryField_1 : '/' field_1 NL? mandatoryField_2 ;

mandatoryField_2 : '/' field_2 NL? (filledOptionalField_3 | emptyOptionalField_3 )? ;

filledOptionalField_3 : '/' field_3 NL? (filledOptionalField_4 | emptyOptionalField_4)? ;
emptyOptionalField_3 : '/' (filledOptionalField_4 | emptyOptionalField_4) ;

filledOptionalField_4 : '/' field_4 NL? filledOptionalField_5? ;
emptyOptionalField_4 : '/' filledOptionalField_5 ;

filledOptionalField_5 : '/' field_5 ;

endRule : NL;

field_1 : (A | N | B | S)+ ;

field_2 : (A | N)+ ;

field_3 : (A | N | B)+ ;

field_4 : A+ ;

field_5 : N+ ;

/* Lexer Rules */

A : [A-Z]+ ;

N : [0-9]+ ;

B : ' ' -> skip ;

S : [*&@#-_<>?!]+ ;

NL : '\r'? '\n' ;


问:
How can I add startDestination programmatically accoridng the value?
How can I add startDestination programmatically according the value for example if the integer variable was 0 then I want to start navigation_main_countries_fragment, Otherwise navigation_main_categories_fragment.

Inside activity_main

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/activity_main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:navGraph="@navigation/navigation_main" //I deleted this line already
    android:layout_weight="1" />
```
<p>Inside <code>navigation_main</code></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/navigation_main_countries_fragment" //I deleted this line already
    tools:ignore="InvalidNavigation">

    <fragment
        android:id="@+id/navigation_main_countries_fragment"
        android:name="com.test.app.fragments.CountriesFragment"
        tools:layout="@layout/fragment_countries" />

    <fragment
        android:id="@+id/navigation_main_categories_fragment"
        android:name="com.test.app.fragments.CategoriesFragment"
        tools:layout="@layout/fragment_categories" />

</navigation>
</code>```

答:
Try this code</p>
```<code>// Configure the navigation
val navHost = nav_host_fragment as NavHostFragment
graph = navHost.navController.navInflater.inflate(R.navigation.nav_graph)
if(value == 0)
graph.startDestination = R.id.counriesFragment
else
grapgh.startDestination = R.id.categoryFragment

navHost.navController.graph = graph

NavigationUI.setupActionBarWithNavController(this, navHost.navController)
</code>```

Body:
How can I add startDestination programmatically according the value for example if the integer variable was 0 then I want to start navigation_main_countries_fragment, Otherwise navigation_main_categories_fragment.

Inside activity_main

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/activity_main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:navGraph="@navigation/navigation_main" //I deleted this line already
    android:layout_weight="1" />

Inside navigation_main

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/navigation_main_countries_fragment" //I deleted this line already
    tools:ignore="InvalidNavigation">

    <fragment
        android:id="@+id/navigation_main_countries_fragment"
        android:name="com.test.app.fragments.CountriesFragment"
        tools:layout="@layout/fragment_countries" />

    <fragment
        android:id="@+id/navigation_main_categories_fragment"
        android:name="com.test.app.fragments.CategoriesFragment"
        tools:layout="@layout/fragment_categories" />

</navigation>

Body:
Try this code

// Configure the navigation
val navHost = nav_host_fragment as NavHostFragment
graph = navHost.navController.navInflater.inflate(R.navigation.nav_graph)
if(value == 0)
graph.startDestination = R.id.counriesFragment
else
grapgh.startDestination = R.id.categoryFragment

navHost.navController.graph = graph

NavigationUI.setupActionBarWithNavController(this, navHost.navController)


问:
How to render multiple update forms in Django
here is my problem.

I have a list of objects that I display in a table and all works just fine except that I would like to edit them inside a modal and submit them using AJAX.

I though that it was a simple idea to render, for each row, a form with the inputs pre-filled and then submit the selected form with AJAX.

I wonder if there is a relatively simplified way to render the UpdateForm without writing manually all the input fields.

Something like this:

```<code><table>
{% for transaction in transactions %}
<tr>
<td>{{ transaction.date|date:"d.m.Y" }}</td>
<td>{{ transaction.amount }}</td>
<td>
  <a href="#" data-bs-toggle="modal" data-bs-target="#edit{{ transaction.id }}">Edit</a>
 <div class="modal" id="edit{{ transaction.id }}">
   {{ transaction_form }}
 </div>
</td>
<tr>
{% endfor %}
</table>
</code>```

But how can I pass the form from the view?

The way I'm currently doing it is that when the user click on edit the page refresh and the modal is displayed with the form prefilled but it is (a) slow to open and (b) I don't think it is a nice way to do it.

This is my current code

views.py

```<code>
class ProjectDetailView(DetailView):
    model = Project
    template_name = "template.html"
    context_object_name = "project"

    def get_transactions(self):
        transactions = Transaction.objects.filter(project=self.get_object())
        return transactions

    def get_transaction_form(self):
        form = TransactionForm()
        if self.request.POST:
            form = TransactionForm(self.request.POST)
        elif 'edit_entry' in self.request.GET:
            form = TransactionForm(instance=self.get_entry())
        return form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['transactions'] = self.get_transactions()
        context['transaction_form'] = self.get_transaction_form()
        return context
</code>```

template.html

```<code><table>
{% for transaction in transactions %}
<tr>
<td>{{ transaction.date|date:"d.m.Y" }}</td>
<td>{{ transaction.amount }}</td>
<td>
  <a href="{{ project.get_absolute_url }}?edit_entry={{ transaction.slug }}">Edit</a>
</td>
<tr>
{% endfor %}
</table>
<div class="modal" id="edit-modal">
   {{ transaction_form }}
</div>
<script>
{% if 'edit_entry' in request.GET %}
  $('#edit-modal').modal('show')
{% endif %}
</script>
</code>```

Thank you for any feedback

答:
This solution needs you work with Javascript to do that,
when the user clicks 'Edit' for an object on your page,

you send AJAX request (using Fetch API or Jquery) to your view,

The view will return HTML of the form and you put this  HTML in the modal's body

Show the modal with an action button to submit the form.

As the user clicks submit, your code submits the form through Ajax, you can use Formdata or AjaxForm for that, the view which return an JSON or HTML which indicates if the data is saved successfully or not.

The problem I'm not a Class-Based View guy so I can't give you specifics from Django side.

Body:
here is my problem.

I have a list of objects that I display in a table and all works just fine except that I would like to edit them inside a modal and submit them using AJAX.

I though that it was a simple idea to render, for each row, a form with the inputs pre-filled and then submit the selected form with AJAX.

I wonder if there is a relatively simplified way to render the UpdateForm without writing manually all the input fields.

Something like this:

{% for transaction in transactions %}

{{ transaction.date|date:"d.m.Y" }}
{{ transaction.amount }}

  Edit

   {{ transaction_form }}

{% endfor %}

But how can I pass the form from the view?

The way I'm currently doing it is that when the user click on edit the page refresh and the modal is displayed with the form prefilled but it is (a) slow to open and (b) I don't think it is a nice way to do it.

This is my current code

views.py

class ProjectDetailView(DetailView):
    model = Project
    template_name = "template.html"
    context_object_name = "project"

    def get_transactions(self):
        transactions = Transaction.objects.filter(project=self.get_object())
        return transactions

    def get_transaction_form(self):
        form = TransactionForm()
        if self.request.POST:
            form = TransactionForm(self.request.POST)
        elif 'edit_entry' in self.request.GET:
            form = TransactionForm(instance=self.get_entry())
        return form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['transactions'] = self.get_transactions()
        context['transaction_form'] = self.get_transaction_form()
        return context

template.html

{% for transaction in transactions %}

{{ transaction.date|date:"d.m.Y" }}
{{ transaction.amount }}

  Edit

{% endfor %}

   {{ transaction_form }}

Thank you for any feedback


问:
This expression is not callable ... type has no call signatures [ts 2349] error
I'm trying to use functions from Observable Plot example with marimekko chart in my project with typescript and got this error on this string:

```<code>   setXz(I.map((i) => sum.get(X[i])))
</code>```

The code is:

```<code>function marimekko({ x, y, z, inset = 0.5, ...options }) {
    const [Xz, setXz] = lazyChannel(z)
    const {
        y1,
        y2,
        transform: stackY,
    } = Plot.stackY({ offset: "expand", x, y: z })
    const {
        x1,
        x2,
        transform: stackX,
    } = Plot.stackX({ offset: "expand", y, x: Xz })
    return {
        x1,
        x2,
        y1,
        y2,
        transform: (data, facets) => {
            const I = d3.range(data.length)
            const X = Plot.valueof(data, x)
            const Z = Plot.valueof(data, z)
            const sum = d3.rollup(
                I,
                (I) => d3.sum(I, (i) => Z[i]),
                (i) => X[i]
            )
            setXz(I.map((i) => sum.get(X[i])))
            stackX(data, facets)
            stackY(data, facets)
            return { data, facets }
        },
        inset,
        ...options,
    }
}

function lazyChannel(source) {
    let value
    return [
        {
            transform: () => value,
            label:
                typeof source === "string"
                    ? source
                    : source
                    ? source.label
                    : undefined,
        },
        (v) => (value = v),
    ]
}
</code>```

Any ideas how to fix it?

答:
You function returns setXz the following type :

```<code>((v: any) => any) | {
  transform: () => any;
  label: any;
}
</code>```

Note the union, it contains an object which is not callable.

That happens because TS does not infer the tuple but returns an array of the unions of the possible types.

You should at least type the return of you function.

```<code>function lazyChannel(source): [{ transform: () => any, label: any}, ((v: any) => any)] {
  let value
  return [
      {
          transform: () => value,
          label:
              typeof source === "string"
                  ? source
                  : source
                  ? source.label
                  : undefined,
      },
      (v) => (value = v),
  ]
}
</code>```

Note that I would advise use to not use any but to specify the types of the parameters & return.

Body:
I'm trying to use functions from Observable Plot example with marimekko chart in my project with typescript and got this error on this string:

   setXz(I.map((i) => sum.get(X[i])))

The code is:

function marimekko({ x, y, z, inset = 0.5, ...options }) {
    const [Xz, setXz] = lazyChannel(z)
    const {
        y1,
        y2,
        transform: stackY,
    } = Plot.stackY({ offset: "expand", x, y: z })
    const {
        x1,
        x2,
        transform: stackX,
    } = Plot.stackX({ offset: "expand", y, x: Xz })
    return {
        x1,
        x2,
        y1,
        y2,
        transform: (data, facets) => {
            const I = d3.range(data.length)
            const X = Plot.valueof(data, x)
            const Z = Plot.valueof(data, z)
            const sum = d3.rollup(
                I,
                (I) => d3.sum(I, (i) => Z[i]),
                (i) => X[i]
            )
            setXz(I.map((i) => sum.get(X[i])))
            stackX(data, facets)
            stackY(data, facets)
            return { data, facets }
        },
        inset,
        ...options,
    }
}

function lazyChannel(source) {
    let value
    return [
        {
            transform: () => value,
            label:
                typeof source === "string"
                    ? source
                    : source
                    ? source.label
                    : undefined,
        },
        (v) => (value = v),
    ]
}

Any ideas how to fix it?

Body:
You function returns setXz the following type :

((v: any) => any) | {
  transform: () => any;
  label: any;
}

Note the union, it contains an object which is not callable.

That happens because TS does not infer the tuple but returns an array of the unions of the possible types.

You should at least type the return of you function.

function lazyChannel(source): [{ transform: () => any, label: any}, ((v: any) => any)] {
  let value
  return [
      {
          transform: () => value,
          label:
              typeof source === "string"
                  ? source
                  : source
                  ? source.label
                  : undefined,
      },
      (v) => (value = v),
  ]
}

Note that I would advise use to not use any but to specify the types of the parameters & return.


问:
Unable to receive proper notification content using Firebase in Angular
I am trying to receive notifications using Firebase in Angular. I do get the notification when it gets triggered. However, the title and the body that should be in the notification do not do so. I have tried various solutions but am unable to do it. At one place, I read at one of the blogs while searching for the solution that it gets the point that it has to push notification, however, it's not able to receive the title and body properly.

Also, it's working fine on React App from Laravel Side, but not in Angular.

The notification I get I am attaching it below. Please guide me.

enter image description here

```<code>const app = initializeApp(firebaseConfig); //firebaseConfig is my firebase configurations
const messaging = getMessaging();
getToken(messaging, { vapidKey: 'BPupbI-8TFUeiPhfTI43JW5BZ7uDd3vAqba1w1YHR3H8mqIswifdGByxr0Vbz0ENqjJyFjOi0ptyqM5w3wBH3bc' })
  .then((currentToken) => {
    if (currentToken) {
      localStorage.setItem('fcm_token', currentToken)
      this.fcm_token = currentToken
      console.log('guest', this.fcm_token)
      // Track the token -> client mapping, by sending to backend server
      // show on the UI that permission is secured
    } else {
      console.log('No registration token available. Request permission to generate one.');

      // shows on the UI that permission is required
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    // catch error while creating client token
  });
  onMessage(messaging, (payload) => {
    alert(1);
    console.log('asdasdasdasdg1')
    console.log('Message received. ', payload, payload.data.body);
    // return
    // ...
  });
</code>```

Also, anywhere this code is, the notification gets triggered whether the onMessage function exists or not. And, I don't think that onMessage gets triggered anyways since the console.log and alert doesn't execute.

答:
Try using old version of Firebase, I was having the same issue with Firebase 9 even though I was using the official documentation.

On Using 8.10 version, it worked like a charm.

Body:
I am trying to receive notifications using Firebase in Angular. I do get the notification when it gets triggered. However, the title and the body that should be in the notification do not do so. I have tried various solutions but am unable to do it. At one place, I read at one of the blogs while searching for the solution that it gets the point that it has to push notification, however, it's not able to receive the title and body properly.

Also, it's working fine on React App from Laravel Side, but not in Angular.

The notification I get I am attaching it below. Please guide me.

enter image description here

const app = initializeApp(firebaseConfig); //firebaseConfig is my firebase configurations
const messaging = getMessaging();
getToken(messaging, { vapidKey: 'BPupbI-8TFUeiPhfTI43JW5BZ7uDd3vAqba1w1YHR3H8mqIswifdGByxr0Vbz0ENqjJyFjOi0ptyqM5w3wBH3bc' })
  .then((currentToken) => {
    if (currentToken) {
      localStorage.setItem('fcm_token', currentToken)
      this.fcm_token = currentToken
      console.log('guest', this.fcm_token)
      // Track the token -> client mapping, by sending to backend server
      // show on the UI that permission is secured
    } else {
      console.log('No registration token available. Request permission to generate one.');

      // shows on the UI that permission is required
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    // catch error while creating client token
  });
  onMessage(messaging, (payload) => {
    alert(1);
    console.log('asdasdasdasdg1')
    console.log('Message received. ', payload, payload.data.body);
    // return
    // ...
  });

Also, anywhere this code is, the notification gets triggered whether the onMessage function exists or not. And, I don't think that onMessage gets triggered anyways since the console.log and alert doesn't execute.


问:
Extracting substring with awk if the string includes regular expressions
I have many strings like this

```<code>i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt
</code>```

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

答:
If the positions of the strings are always after the same number of forward slashes, you can print the 2nd and the 6th field, setting the field separator to /

```<code>echo "$i" | awk -F"/" '{print $2, $6}'
</code>```

Output

```<code>M1 FCT
</code>```

You might also use gnu awk and a pattern with 2 capture groups matching the following Cus for the first match, and starting with F for the second match.

The negated character class [^\/]* matches 0 or more characters except a /

```<code>echo "$i" | awk 'match($0, /[^\/]*\/([^\/]*)\/Cus.*\/(F[^\/]*)/, a) {print a[1], a[2]}'
</code>```

Body:
I have many strings like this

i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

Body:
If the positions of the strings are always after the same number of forward slashes, you can print the 2nd and the 6th field, setting the field separator to /

echo "$i" | awk -F"/" '{print $2, $6}'

Output

M1 FCT

You might also use gnu awk and a pattern with 2 capture groups matching the following Cus for the first match, and starting with F for the second match.

The negated character class [^\/]* matches 0 or more characters except a /

echo "$i" | awk 'match($0, /[^\/]*\/([^\/]*)\/Cus.*\/(F[^\/]*)/, a) {print a[1], a[2]}'


问:
TypoScript MenuProcessor special = directory :: page type shortcut
I've defined the following typoscript or my ce:

```<code>dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
    10 {
        special = directory
        special.value.field = pages
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            20 {
                references.fieldName = teaser_image
                as = teaserImage
            }
        }
    }
}
</code>```

The value for pages comes from the configuration in the be (select page from pagetree).

This works well, but if a page with type shortcut (4) is selected, nothing will be generated. I am looking for a way to achieve that if a shortcut is selected, the menu for the target page of this shortcut is being generated.

I want to solve this explicitly for the page type shortcut, not for the page type mountpoint. Unfortunately, I still don't get any data in the variable menu when the page type is shortcut.

答:
For clarification that's the whole typoscript for the ce:

```<code> ############################################
#### CTYPE:menu_distribution ####
############################################
tt_content.menu_distribution =< lib.contentElement
tt_content.menu_distribution {
    templateName = MenuDistribution
    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
        10 {
            special = directory
            special.value.field = pages
            as = menu
            dataProcessing {
                10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                10 {
                    references.fieldName = media
                }
                20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                20 {
                    references.fieldName = teaser_image
                    as = teaserImage
                }
            }
        }
    }
    stdWrap {
        editIcons = tt_content: header [header_layout], pages
        editIcons {
            iconTitle.data = LLL:EXT:fluid_styled_content/Resources/Private/Language/FrontendEditing.xlf:editIcon.menu
        }
    }
}
</code>```

In the template for the ce the variable menu contains nothing, if a page of type shortcut is selected.

TCA:

```<code>'pages' => [
                'exclude' => true,
                'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.startingpoint',
                'config' => [
                    'type' => 'group',
                    'internal_type' => 'db',
                    'allowed' => 'pages',
                    'size' => 3,
                    'maxitems' => 1,
                    'minitems' => 1
                ]
            ],
</code>```

Body:
I've defined the following typoscript or my ce:

dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
    10 {
        special = directory
        special.value.field = pages
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            20 {
                references.fieldName = teaser_image
                as = teaserImage
            }
        }
    }
}

The value for pages comes from the configuration in the be (select page from pagetree).

This works well, but if a page with type shortcut (4) is selected, nothing will be generated. I am looking for a way to achieve that if a shortcut is selected, the menu for the target page of this shortcut is being generated.

I want to solve this explicitly for the page type shortcut, not for the page type mountpoint. Unfortunately, I still don't get any data in the variable menu when the page type is shortcut.

Body:
For clarification that's the whole typoscript for the ce:

 ############################################
#### CTYPE:menu_distribution ####
############################################
tt_content.menu_distribution =< lib.contentElement
tt_content.menu_distribution {
    templateName = MenuDistribution
    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
        10 {
            special = directory
            special.value.field = pages
            as = menu
            dataProcessing {
                10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                10 {
                    references.fieldName = media
                }
                20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                20 {
                    references.fieldName = teaser_image
                    as = teaserImage
                }
            }
        }
    }
    stdWrap {
        editIcons = tt_content: header [header_layout], pages
        editIcons {
            iconTitle.data = LLL:EXT:fluid_styled_content/Resources/Private/Language/FrontendEditing.xlf:editIcon.menu
        }
    }
}

In the template for the ce the variable menu contains nothing, if a page of type shortcut is selected.

TCA:

'pages' => [
                'exclude' => true,
                'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.startingpoint',
                'config' => [
                    'type' => 'group',
                    'internal_type' => 'db',
                    'allowed' => 'pages',
                    'size' => 3,
                    'maxitems' => 1,
                    'minitems' => 1
                ]
            ],


问:
SwiftLint cannot exclude the nested files
I try to exclude all the unit test files. But it does not work. Does SwiftLint support nested exclude?</p>
```<code>  - Pods
  - Carthage
  - ".*Tests.swift"
# Errors
force_try: warning #All errors occur in Nimble pod, this can be ignored
force_cast:
  severity: warning
  excluded:
    - "*Tests.swift"
</code>```

答:
You can include folder path in the excluded path section, For nested file workaround, try keeping it in a single folder to exclude the files or mention them in exclude file section.

For Example

```<code>excluded: # paths to ignore during linting. Takes precedence over `included`.
  - pH7-DriverTests
  - pH7-DriverUITests
  - Pods
</code>```

Example:- project's Test & UITest folder name is 'pH7-DriverTest' and 'pH7-DriverUITest' and it contains in source folder.

Body:
I try to exclude all the unit test files. But it does not work. Does SwiftLint support nested exclude?

  - Pods
  - Carthage
  - ".*Tests.swift"
# Errors
force_try: warning #All errors occur in Nimble pod, this can be ignored
force_cast:
  severity: warning
  excluded:
    - "*Tests.swift"

Body:
You can include folder path in the excluded path section, For nested file workaround, try keeping it in a single folder to exclude the files or mention them in exclude file section.

For Example

excluded: # paths to ignore during linting. Takes precedence over `included`.
  - pH7-DriverTests
  - pH7-DriverUITests
  - Pods

Example:- project's Test & UITest folder name is 'pH7-DriverTest' and 'pH7-DriverUITest' and it contains in source folder.


问:
How to sort by first few letters of string?
For example, if I have an array of strings {"Bob", "Bom", "Ash", "Ben"}, how do I sort it first by first letter (ASCII value), then by second letter, and so on without losing the previous sorted order? so after sorting it would become {"Ash", "Ben", "Bob", "Bom"}?

答:
You can use Arrays methods in util package

```<code>import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      String[] ar = {"Bob", "Bom", "Ash", "Ben"};
      Arrays.sort(ar);
      System.out.println(Arrays.toString(ar));
    }
}
</code>```

Body:
You can use Arrays methods in util package

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      String[] ar = {"Bob", "Bom", "Ash", "Ben"};
      Arrays.sort(ar);
      System.out.println(Arrays.toString(ar));
    }
}


问:
CBC solver Result - Linear relaxation infeasible
I am trying to solve an LP problem with the CBC solver in Linux.

When I try t solve it, the model is determined linearly infeasible but a solution is found, so I don't understand why this is happening.

This is the solver output:

```<code>Welcome to the CBC MILP Solver
Version: 2.10.5
Build Date: Oct 15 2020

command line - cbc tt2.lp solve printing csv solu sol.txt (default strategy 1)
Presolve determined that the problem was infeasible with tolerance of 1e-08
Analysis indicates model infeasible or unbounded
Perturbing problem by 0.001% of 6368.0221 - largest nonzero change 9.6555471e-05 ( 8.8302642e-05%) - largest zero change 6.095558e-05
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 6484.7494 (8)
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 1.437715e+13 (28)
36  Obj -16980 Primal inf 105.38866 (21) Dual inf 7.2658581e+12 (14) w.o. free dual inf (13)
58  Obj -16046.434 Primal inf 0.28949488 (2)
Primal infeasible - objective value -16046.434
PrimalInfeasible objective -16046.43383 - 58 iterations time 0.002

Result - Linear relaxation infeasible

Enumerated nodes:           0
Total iterations:           0
Time (CPU seconds):         0.01
Time (Wallclock Seconds):   0.02

Option for printingOptions changed from normal to csv
Total time (CPU seconds):       0.01   (Wallclock seconds):       0.03
</code>```

I turned off preprocessing to see if it made any changes but it didn't.

```<code>Welcome to the CBC MILP Solver
Version: 2.10.5
Build Date: Oct 15 2020

command line - cbc tt2.lp preprocess off passp 0 solve printing csv solu sol.txt (default strategy 1)
Option for preprocess changed from sos to off
passPresolve was changed from 5 to 0
Perturbing problem by 0.001% of 6368.0221 - largest nonzero change 9.6555471e-05 ( 8.8302642e-05%) - largest zero change 6.095558e-05
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 6484.7494 (8)
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 1.437715e+13 (28)
36  Obj -16980 Primal inf 105.38866 (21) Dual inf 7.2658581e+12 (14) w.o. free dual inf (13)
58  Obj -16046.434 Primal inf 0.28949488 (2)
Primal infeasible - objective value -16046.434
PrimalInfeasible objective -16046.43383 - 58 iterations time 0.002

Result - Linear relaxation infeasible

Enumerated nodes:           0
Total iterations:           0
Time (CPU seconds):         0.00
Time (Wallclock Seconds):   0.02

Option for printingOptions changed from normal to csv
Total time (CPU seconds):       0.00   (Wallclock seconds):       0.03
</code>```

So the problem is that the Linear Relaxation of the LP problem is infeasible, but I don't know what this means or how to solve it.

This is the LP file in case it helps.

```<code>Minimize
    1.0 cv_1_1 - 1.0 w_1_1 + 2.0 cv_2_1 - 2.0 w_2_1 + 4.0 cv_1_2 - 4.0 w_1_2 + 8.0 cv_2_2 - 8.0 w_2_2 + 9.0 cv_1_3 - 9.0 w_1_3 + 18.0 cv_2_3 - 18.0 w_2_3 + 16.0 cv_1_4 - 16.0 w_1_4 + 32.0 cv_2_4 - 32.0 w_2_4 + 1 dmv_2_1 + 1 dmv_2_2

Subject To

    \Manipulated variables: initial value
    R0: mv_1_0 = 150
    R1: mv_2_0 = 150

    \States: initial value
    R2: x_1_0 = 0.03534155
    R3: x_2_0 = 0.07947994
    R4: x_3_0 = -0.00548606
    R5: x_4_0 = -0.28400902

    \Manipulated variables: change variables
    R6: dmv_1_1 - mv_1_1 + mv_1_0 = 0
    R7: dmv_1_2 - mv_1_2 + mv_1_1 = 0
    R8: dmv_1_3 - mv_1_3 + mv_1_2 = 0
    R9: dmv_1_4 - mv_1_4 + mv_1_3 = 0
    R10: dmv_2_1 - mv_2_1 + mv_2_0 = 0
    R11: dmv_2_2 - mv_2_2 + mv_2_1 = 0
    R12: dmv_2_3 - mv_2_3 + mv_2_2 = 0
    R13: dmv_2_4 - mv_2_4 + mv_2_3 = 0

    \Controlled variables: upper and lower bounds
    R14: cv_1_1 >= 45
    R15: cv_1_1 <= 65
    R16: cv_1_2 >= 45
    R17: cv_1_2 <= 65
    R18: cv_1_3 >= 45
    R19: cv_1_3 <= 65
    R20: cv_1_4 >= 45
    R21: cv_1_4 <= 65
    R22: cv_2_1 >= 5
    R23: cv_2_1 <= 11
    R24: cv_2_2 >= 5
    R25: cv_2_2 <= 11
    R26: cv_2_3 >= 5
    R27: cv_2_3 <= 11
    R28: cv_2_4 >= 5
    R29: cv_2_4 <= 11

    \Manipulated variables: ratio change allowed
    R30: dmv_1_1 <= 1
    R31: dmv_1_1 >= -1
    R32: dmv_1_2 <= 1
    R33: dmv_1_2 >= -1
    R34: dmv_1_3 <= 0.0
    R35: dmv_1_3 >= -0.0
    R36: dmv_1_4 <= 0.0
    R37: dmv_1_4 >= -0.0
    R38: dmv_2_1 <= 1
    R39: dmv_2_1 >= -1
    R40: dmv_2_2 <= 1
    R41: dmv_2_2 >= -1
    R42: dmv_2_3 <= 0.0
    R43: dmv_2_3 >= -0.0
    R44: dmv_2_4 <= 0.0
    R45: dmv_2_4 >= -0.0

    \Manipulated variables: upper and lower bounds
    R46: mv_1_1 >= 140
    R47: mv_1_1 <= 170
    R48: mv_1_2 >= 140
    R49: mv_1_2 <= 170
    R50: mv_1_3 >= 140
    R51: mv_1_3 <= 170
    R52: mv_1_4 >= 140
    R53: mv_1_4 <= 170
    R54: mv_2_1 >= 130
    R55: mv_2_1 <= 150
    R56: mv_2_2 >= 130
    R57: mv_2_2 <= 150
    R58: mv_2_3 >= 130
    R59: mv_2_3 <= 150
    R60: mv_2_4 >= 130
    R61: mv_2_4 <= 150

    \W: reference trajectories for controlled variables
    R62: w_1_1 = 10.0
    R63: w_1_2 = 40.0
    R64: w_1_3 = 90.0
    R65: w_1_4 = 160.0
    R66: w_2_1 = 20.0
    R67: w_2_2 = 80.0
    R68: w_2_3 = 180.0
    R69: w_2_4 = 320.0

    \Model
    \X(t+1) - Gx(t) - Hmv(t) = 0
    \cv(t) - Cx(t) = 0

    R70: x_1_2 - 1.001 x_1_1 + 0.0001777 x_2_1 + 0.02923 x_3_1 + 0.001065 x_4_1 - 5.049e-06 mv_1_1 + 8.92e-06 mv_2_1 = 0
    R71: x_2_2 - 0.001961 x_1_1 - 0.9536 x_2_1 - 0.009859 x_3_1 + 0.08002 x_4_1 - 9.27e-06 mv_1_1 + 0.0001443 mv_2_1 = 0
    R72: x_3_2 - 0.02647 x_1_1 + 0.006174 x_2_1 - 0.9386 x_3_1 + 0.07591 x_4_1 - 5.375e-05 mv_1_1 + 0.000216 mv_2_1 = 0
    R73: x_4_2 + 0.001008 x_1_1 - 0.2273 x_2_1 - 0.04935 x_3_1 - 0.6928 x_4_1 - 0.000377 mv_1_1 + 0.001151 mv_2_1 = 0
    R74: cv_1_1 - 1408.0 x_1_1 + 10.67 x_2_1 + 19.4 x_3_1 - 0.6612 x_4_1 = 0
    R75: cv_2_1 - 4.282 x_1_1 - 77.07 x_2_1 - 0.1379 x_3_1 + 2.884 x_4_1 = 0
    R76: x_1_3 - 1.001 x_1_2 + 0.0001777 x_2_2 + 0.02923 x_3_2 + 0.001065 x_4_2 - 5.049e-06 mv_1_2 + 8.92e-06 mv_2_2 = 0
    R77: x_2_3 - 0.001961 x_1_2 - 0.9536 x_2_2 - 0.009859 x_3_2 + 0.08002 x_4_2 - 9.27e-06 mv_1_2 + 0.0001443 mv_2_2 = 0
    R78: x_3_3 - 0.02647 x_1_2 + 0.006174 x_2_2 - 0.9386 x_3_2 + 0.07591 x_4_2 - 5.375e-05 mv_1_2 + 0.000216 mv_2_2 = 0
    R79: x_4_3 + 0.001008 x_1_2 - 0.2273 x_2_2 - 0.04935 x_3_2 - 0.6928 x_4_2 - 0.000377 mv_1_2 + 0.001151 mv_2_2 = 0
    R80: cv_1_2 - 1408.0 x_1_2 + 10.67 x_2_2 + 19.4 x_3_2 - 0.6612 x_4_2 = 0
    R81: cv_2_2 - 4.282 x_1_2 - 77.07 x_2_2 - 0.1379 x_3_2 + 2.884 x_4_2 = 0
    R82: x_1_4 - 1.001 x_1_3 + 0.0001777 x_2_3 + 0.02923 x_3_3 + 0.001065 x_4_3 - 5.049e-06 mv_1_3 + 8.92e-06 mv_2_3 = 0
    R83: x_2_4 - 0.001961 x_1_3 - 0.9536 x_2_3 - 0.009859 x_3_3 + 0.08002 x_4_3 - 9.27e-06 mv_1_3 + 0.0001443 mv_2_3 = 0
    R84: x_3_4 - 0.02647 x_1_3 + 0.006174 x_2_3 - 0.9386 x_3_3 + 0.07591 x_4_3 - 5.375e-05 mv_1_3 + 0.000216 mv_2_3 = 0
    R85: x_4_4 + 0.001008 x_1_3 - 0.2273 x_2_3 - 0.04935 x_3_3 - 0.6928 x_4_3 - 0.000377 mv_1_3 + 0.001151 mv_2_3 = 0
    R86: cv_1_3 - 1408.0 x_1_3 + 10.67 x_2_3 + 19.4 x_3_3 - 0.6612 x_4_3 = 0
    R87: cv_2_3 - 4.282 x_1_3 - 77.07 x_2_3 - 0.1379 x_3_3 + 2.884 x_4_3 = 0
    R88: x_1_5 - 1.001 x_1_4 + 0.0001777 x_2_4 + 0.02923 x_3_4 + 0.001065 x_4_4 - 5.049e-06 mv_1_4 + 8.92e-06 mv_2_4 = 0
    R89: x_2_5 - 0.001961 x_1_4 - 0.9536 x_2_4 - 0.009859 x_3_4 + 0.08002 x_4_4 - 9.27e-06 mv_1_4 + 0.0001443 mv_2_4 = 0
    R90: x_3_5 - 0.02647 x_1_4 + 0.006174 x_2_4 - 0.9386 x_3_4 + 0.07591 x_4_4 - 5.375e-05 mv_1_4 + 0.000216 mv_2_4 = 0
    R91: x_4_5 + 0.001008 x_1_4 - 0.2273 x_2_4 - 0.04935 x_3_4 - 0.6928 x_4_4 - 0.000377 mv_1_4 + 0.001151 mv_2_4 = 0
    R92: cv_1_4 - 1408.0 x_1_4 + 10.67 x_2_4 + 19.4 x_3_4 - 0.6612 x_4_4 = 0
    R93: cv_2_4 - 4.282 x_1_4 - 77.07 x_2_4 - 0.1379 x_3_4 + 2.884 x_4_4 = 0

Bounds
    \States: upper and lower bounds
    x_1_1 free
    x_1_2 free
    x_1_3 free
    x_1_4 free
    x_1_5 free
    x_2_1 free
    x_2_2 free
    x_2_3 free
    x_2_4 free
    x_2_5 free
    x_3_1 free
    x_3_2 free
    x_3_3 free
    x_3_4 free
    x_3_5 free
    x_4_1 free
    x_4_2 free
    x_4_3 free
    x_4_4 free
    x_4_5 free

 End

</code>```

答:
Disclaimer: I somewhat despise those txt-based serialization-formats and this means, that i'm not an expert because i don't use them often.

My guess:

Variables are by default non-negative

Lower-bound: 0.0

Upper-bound: positive infinity

This is a very common design-decision in various solvers and in regards to the LP-file i guess it might be true too (?).

(A quick glimpse through Gurobi, CPLEX, FICO commercial solvers make me think all of those apply this logic -> CoinOR Clp/Cbc probably does the same)

A:
Let's take some other solver and run your file:

infeasible

says: R4: x_3_0 = -0.00548606 is not okay (there might be other source of infeasibility)

B:
Your lp-file contains:

```<code>Bounds
    \States: upper and lower bounds
    x_1_1 free
    ...
</code>```

Free variables are [-infinity, +infinity] variables -> not non-negative

Seeing those explicitly here somewhat indicates a potential default as we guess above

C:

x_3_0 does not appear in free-vars

x_3_0 is probably in [0, +infinity)

Obviously incompatible with R4: x_3_0 = -0.00548606

And it's such a simple deduction, that presolving recognizes that

Body:
I am trying to solve an LP problem with the CBC solver in Linux.

When I try t solve it, the model is determined linearly infeasible but a solution is found, so I don't understand why this is happening.

This is the solver output:

Welcome to the CBC MILP Solver
Version: 2.10.5
Build Date: Oct 15 2020

command line - cbc tt2.lp solve printing csv solu sol.txt (default strategy 1)
Presolve determined that the problem was infeasible with tolerance of 1e-08
Analysis indicates model infeasible or unbounded
Perturbing problem by 0.001% of 6368.0221 - largest nonzero change 9.6555471e-05 ( 8.8302642e-05%) - largest zero change 6.095558e-05
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 6484.7494 (8)
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 1.437715e+13 (28)
36  Obj -16980 Primal inf 105.38866 (21) Dual inf 7.2658581e+12 (14) w.o. free dual inf (13)
58  Obj -16046.434 Primal inf 0.28949488 (2)
Primal infeasible - objective value -16046.434
PrimalInfeasible objective -16046.43383 - 58 iterations time 0.002

Result - Linear relaxation infeasible

Enumerated nodes:           0
Total iterations:           0
Time (CPU seconds):         0.01
Time (Wallclock Seconds):   0.02

Option for printingOptions changed from normal to csv
Total time (CPU seconds):       0.01   (Wallclock seconds):       0.03

I turned off preprocessing to see if it made any changes but it didn't.

Welcome to the CBC MILP Solver
Version: 2.10.5
Build Date: Oct 15 2020

command line - cbc tt2.lp preprocess off passp 0 solve printing csv solu sol.txt (default strategy 1)
Option for preprocess changed from sos to off
passPresolve was changed from 5 to 0
Perturbing problem by 0.001% of 6368.0221 - largest nonzero change 9.6555471e-05 ( 8.8302642e-05%) - largest zero change 6.095558e-05
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 6484.7494 (8)
0  Obj 0 Primal inf 1303.3614 (30) Dual inf 1.437715e+13 (28)
36  Obj -16980 Primal inf 105.38866 (21) Dual inf 7.2658581e+12 (14) w.o. free dual inf (13)
58  Obj -16046.434 Primal inf 0.28949488 (2)
Primal infeasible - objective value -16046.434
PrimalInfeasible objective -16046.43383 - 58 iterations time 0.002

Result - Linear relaxation infeasible

Enumerated nodes:           0
Total iterations:           0
Time (CPU seconds):         0.00
Time (Wallclock Seconds):   0.02

Option for printingOptions changed from normal to csv
Total time (CPU seconds):       0.00   (Wallclock seconds):       0.03

So the problem is that the Linear Relaxation of the LP problem is infeasible, but I don't know what this means or how to solve it.

This is the LP file in case it helps.

Minimize
    1.0 cv_1_1 - 1.0 w_1_1 + 2.0 cv_2_1 - 2.0 w_2_1 + 4.0 cv_1_2 - 4.0 w_1_2 + 8.0 cv_2_2 - 8.0 w_2_2 + 9.0 cv_1_3 - 9.0 w_1_3 + 18.0 cv_2_3 - 18.0 w_2_3 + 16.0 cv_1_4 - 16.0 w_1_4 + 32.0 cv_2_4 - 32.0 w_2_4 + 1 dmv_2_1 + 1 dmv_2_2

Subject To

    \Manipulated variables: initial value
    R0: mv_1_0 = 150
    R1: mv_2_0 = 150

    \States: initial value
    R2: x_1_0 = 0.03534155
    R3: x_2_0 = 0.07947994
    R4: x_3_0 = -0.00548606
    R5: x_4_0 = -0.28400902

    \Manipulated variables: change variables
    R6: dmv_1_1 - mv_1_1 + mv_1_0 = 0
    R7: dmv_1_2 - mv_1_2 + mv_1_1 = 0
    R8: dmv_1_3 - mv_1_3 + mv_1_2 = 0
    R9: dmv_1_4 - mv_1_4 + mv_1_3 = 0
    R10: dmv_2_1 - mv_2_1 + mv_2_0 = 0
    R11: dmv_2_2 - mv_2_2 + mv_2_1 = 0
    R12: dmv_2_3 - mv_2_3 + mv_2_2 = 0
    R13: dmv_2_4 - mv_2_4 + mv_2_3 = 0

    \Controlled variables: upper and lower bounds
    R14: cv_1_1 >= 45
    R15: cv_1_1 <= 65
    R16: cv_1_2 >= 45
    R17: cv_1_2 <= 65
    R18: cv_1_3 >= 45
    R19: cv_1_3 <= 65
    R20: cv_1_4 >= 45
    R21: cv_1_4 <= 65
    R22: cv_2_1 >= 5
    R23: cv_2_1 <= 11
    R24: cv_2_2 >= 5
    R25: cv_2_2 <= 11
    R26: cv_2_3 >= 5
    R27: cv_2_3 <= 11
    R28: cv_2_4 >= 5
    R29: cv_2_4 <= 11

    \Manipulated variables: ratio change allowed
    R30: dmv_1_1 <= 1
    R31: dmv_1_1 >= -1
    R32: dmv_1_2 <= 1
    R33: dmv_1_2 >= -1
    R34: dmv_1_3 <= 0.0
    R35: dmv_1_3 >= -0.0
    R36: dmv_1_4 <= 0.0
    R37: dmv_1_4 >= -0.0
    R38: dmv_2_1 <= 1
    R39: dmv_2_1 >= -1
    R40: dmv_2_2 <= 1
    R41: dmv_2_2 >= -1
    R42: dmv_2_3 <= 0.0
    R43: dmv_2_3 >= -0.0
    R44: dmv_2_4 <= 0.0
    R45: dmv_2_4 >= -0.0

    \Manipulated variables: upper and lower bounds
    R46: mv_1_1 >= 140
    R47: mv_1_1 <= 170
    R48: mv_1_2 >= 140
    R49: mv_1_2 <= 170
    R50: mv_1_3 >= 140
    R51: mv_1_3 <= 170
    R52: mv_1_4 >= 140
    R53: mv_1_4 <= 170
    R54: mv_2_1 >= 130
    R55: mv_2_1 <= 150
    R56: mv_2_2 >= 130
    R57: mv_2_2 <= 150
    R58: mv_2_3 >= 130
    R59: mv_2_3 <= 150
    R60: mv_2_4 >= 130
    R61: mv_2_4 <= 150

    \W: reference trajectories for controlled variables
    R62: w_1_1 = 10.0
    R63: w_1_2 = 40.0
    R64: w_1_3 = 90.0
    R65: w_1_4 = 160.0
    R66: w_2_1 = 20.0
    R67: w_2_2 = 80.0
    R68: w_2_3 = 180.0
    R69: w_2_4 = 320.0

    \Model
    \X(t+1) - Gx(t) - Hmv(t) = 0
    \cv(t) - Cx(t) = 0

    R70: x_1_2 - 1.001 x_1_1 + 0.0001777 x_2_1 + 0.02923 x_3_1 + 0.001065 x_4_1 - 5.049e-06 mv_1_1 + 8.92e-06 mv_2_1 = 0
    R71: x_2_2 - 0.001961 x_1_1 - 0.9536 x_2_1 - 0.009859 x_3_1 + 0.08002 x_4_1 - 9.27e-06 mv_1_1 + 0.0001443 mv_2_1 = 0
    R72: x_3_2 - 0.02647 x_1_1 + 0.006174 x_2_1 - 0.9386 x_3_1 + 0.07591 x_4_1 - 5.375e-05 mv_1_1 + 0.000216 mv_2_1 = 0
    R73: x_4_2 + 0.001008 x_1_1 - 0.2273 x_2_1 - 0.04935 x_3_1 - 0.6928 x_4_1 - 0.000377 mv_1_1 + 0.001151 mv_2_1 = 0
    R74: cv_1_1 - 1408.0 x_1_1 + 10.67 x_2_1 + 19.4 x_3_1 - 0.6612 x_4_1 = 0
    R75: cv_2_1 - 4.282 x_1_1 - 77.07 x_2_1 - 0.1379 x_3_1 + 2.884 x_4_1 = 0
    R76: x_1_3 - 1.001 x_1_2 + 0.0001777 x_2_2 + 0.02923 x_3_2 + 0.001065 x_4_2 - 5.049e-06 mv_1_2 + 8.92e-06 mv_2_2 = 0
    R77: x_2_3 - 0.001961 x_1_2 - 0.9536 x_2_2 - 0.009859 x_3_2 + 0.08002 x_4_2 - 9.27e-06 mv_1_2 + 0.0001443 mv_2_2 = 0
    R78: x_3_3 - 0.02647 x_1_2 + 0.006174 x_2_2 - 0.9386 x_3_2 + 0.07591 x_4_2 - 5.375e-05 mv_1_2 + 0.000216 mv_2_2 = 0
    R79: x_4_3 + 0.001008 x_1_2 - 0.2273 x_2_2 - 0.04935 x_3_2 - 0.6928 x_4_2 - 0.000377 mv_1_2 + 0.001151 mv_2_2 = 0
    R80: cv_1_2 - 1408.0 x_1_2 + 10.67 x_2_2 + 19.4 x_3_2 - 0.6612 x_4_2 = 0
    R81: cv_2_2 - 4.282 x_1_2 - 77.07 x_2_2 - 0.1379 x_3_2 + 2.884 x_4_2 = 0
    R82: x_1_4 - 1.001 x_1_3 + 0.0001777 x_2_3 + 0.02923 x_3_3 + 0.001065 x_4_3 - 5.049e-06 mv_1_3 + 8.92e-06 mv_2_3 = 0
    R83: x_2_4 - 0.001961 x_1_3 - 0.9536 x_2_3 - 0.009859 x_3_3 + 0.08002 x_4_3 - 9.27e-06 mv_1_3 + 0.0001443 mv_2_3 = 0
    R84: x_3_4 - 0.02647 x_1_3 + 0.006174 x_2_3 - 0.9386 x_3_3 + 0.07591 x_4_3 - 5.375e-05 mv_1_3 + 0.000216 mv_2_3 = 0
    R85: x_4_4 + 0.001008 x_1_3 - 0.2273 x_2_3 - 0.04935 x_3_3 - 0.6928 x_4_3 - 0.000377 mv_1_3 + 0.001151 mv_2_3 = 0
    R86: cv_1_3 - 1408.0 x_1_3 + 10.67 x_2_3 + 19.4 x_3_3 - 0.6612 x_4_3 = 0
    R87: cv_2_3 - 4.282 x_1_3 - 77.07 x_2_3 - 0.1379 x_3_3 + 2.884 x_4_3 = 0
    R88: x_1_5 - 1.001 x_1_4 + 0.0001777 x_2_4 + 0.02923 x_3_4 + 0.001065 x_4_4 - 5.049e-06 mv_1_4 + 8.92e-06 mv_2_4 = 0
    R89: x_2_5 - 0.001961 x_1_4 - 0.9536 x_2_4 - 0.009859 x_3_4 + 0.08002 x_4_4 - 9.27e-06 mv_1_4 + 0.0001443 mv_2_4 = 0
    R90: x_3_5 - 0.02647 x_1_4 + 0.006174 x_2_4 - 0.9386 x_3_4 + 0.07591 x_4_4 - 5.375e-05 mv_1_4 + 0.000216 mv_2_4 = 0
    R91: x_4_5 + 0.001008 x_1_4 - 0.2273 x_2_4 - 0.04935 x_3_4 - 0.6928 x_4_4 - 0.000377 mv_1_4 + 0.001151 mv_2_4 = 0
    R92: cv_1_4 - 1408.0 x_1_4 + 10.67 x_2_4 + 19.4 x_3_4 - 0.6612 x_4_4 = 0
    R93: cv_2_4 - 4.282 x_1_4 - 77.07 x_2_4 - 0.1379 x_3_4 + 2.884 x_4_4 = 0

Bounds
    \States: upper and lower bounds
    x_1_1 free
    x_1_2 free
    x_1_3 free
    x_1_4 free
    x_1_5 free
    x_2_1 free
    x_2_2 free
    x_2_3 free
    x_2_4 free
    x_2_5 free
    x_3_1 free
    x_3_2 free
    x_3_3 free
    x_3_4 free
    x_3_5 free
    x_4_1 free
    x_4_2 free
    x_4_3 free
    x_4_4 free
    x_4_5 free

 End

Body:
Disclaimer: I somewhat despise those txt-based serialization-formats and this means, that i'm not an expert because i don't use them often.

My guess:

Variables are by default non-negative

Lower-bound: 0.0

Upper-bound: positive infinity

This is a very common design-decision in various solvers and in regards to the LP-file i guess it might be true too (?).

(A quick glimpse through Gurobi, CPLEX, FICO commercial solvers make me think all of those apply this logic -> CoinOR Clp/Cbc probably does the same)

A:
Let's take some other solver and run your file:

infeasible

says: R4: x_3_0 = -0.00548606 is not okay (there might be other source of infeasibility)

B:
Your lp-file contains:

Bounds
    \States: upper and lower bounds
    x_1_1 free
    ...

Free variables are [-infinity, +infinity] variables -> not non-negative

Seeing those explicitly here somewhat indicates a potential default as we guess above

C:

x_3_0 does not appear in free-vars

x_3_0 is probably in [0, +infinity)

Obviously incompatible with R4: x_3_0 = -0.00548606

And it's such a simple deduction, that presolving recognizes that


问:
Write a query to add a flag to each user if they've added a new employer in the current year
```<code>    employers table

    column  type
    user_id integer
    year    string
    employer_ein    string
</code>```

We're given a table called employers that consists of a user_id, year, and employer EIN label. Users can have multiple employers dictated by the different EIN labels.
Write a query to add a flag to each user if they've added a new employer in the current year.

```<code>   Example:

   employer

   user_id    year    employer_ein
   # 34323      2018    A
   # 34323      2018    B
   # 34323      2018    C
   # 34323      2017    F
   # 34323      2017    A
   # 34323      2017    B

   # 86323      2018    A
   # 86323      2018    B
   # 86323      2018    C
   # 86323      2017    B
   #
   # 98787      2018    A
   # 98787      2018    B
   # 98787      2018    F
   # 98787      2017    F
   # 98787      2017    B
   # 98787      2017    A
   #
   # 55559      2018    A
   # 55559      2018    B
   # 55559      2018    C

   # Output
   # user_id    year    new_ein_flag
   # 34323      2018      1
   # 86323      2018      1
   # 98787      2018      0
</code>```

答:
```<code>    select user_id,max(year) as year, max(sumrow) as maxsumrow,
(case min(sumrow) = 1 and max(sumrow) = 2 when TRUE then 1 when FALSE then 0 end) as new_ein_flag
from
(SELECT user_id,count(*) as sumrow, max(year) as year,employer_ein FROM `ein` GROUP BY user_id,employer_ein) as grouptable
where year = (select max(year) as maxyear from ein)
group by user_id
 having max(sumrow)=2
</code>```

I tried it. it is screenshot;

Body:
    employers table

    column  type
    user_id integer
    year    string
    employer_ein    string

We're given a table called employers that consists of a user_id, year, and employer EIN label. Users can have multiple employers dictated by the different EIN labels.
Write a query to add a flag to each user if they've added a new employer in the current year.

   Example:

   employer

   user_id    year    employer_ein
   # 34323      2018    A
   # 34323      2018    B
   # 34323      2018    C
   # 34323      2017    F
   # 34323      2017    A
   # 34323      2017    B

   # 86323      2018    A
   # 86323      2018    B
   # 86323      2018    C
   # 86323      2017    B
   #
   # 98787      2018    A
   # 98787      2018    B
   # 98787      2018    F
   # 98787      2017    F
   # 98787      2017    B
   # 98787      2017    A
   #
   # 55559      2018    A
   # 55559      2018    B
   # 55559      2018    C

   # Output
   # user_id    year    new_ein_flag
   # 34323      2018      1
   # 86323      2018      1
   # 98787      2018      0

Body:
    select user_id,max(year) as year, max(sumrow) as maxsumrow,
(case min(sumrow) = 1 and max(sumrow) = 2 when TRUE then 1 when FALSE then 0 end) as new_ein_flag
from
(SELECT user_id,count(*) as sumrow, max(year) as year,employer_ein FROM `ein` GROUP BY user_id,employer_ein) as grouptable
where year = (select max(year) as maxyear from ein)
group by user_id
 having max(sumrow)=2

I tried it. it is screenshot;


问:
vue.js How to get Label from selected Radio Button to show in Preview
I have a form built with bootstrap-vue. The form contains some Radio buttons. I do have a preview button which should show what was selected, but instead of the value from the radio button I would like the label. The radio button code looks something like this:

```<code>  <b-form-group label="Location">
  <b-form-radio-group
    v-model="selectedLocation"
    :options="options"
    :aria-describedby="ariaDescribedby"
    name="radio-inline"
  ></b-form-radio-group>
  </b-form-group>

  <b-button variant="primary" @click="handlePreview()"><i class="fas fa-clipboard-check"></i> Preview</b-button>
</code>```

My script looks something like below:

```<code>data() {
  return {
    selectedLocation: '1',

    options: [
      { text: 'Location1', value: '1' },
      { text: 'Location2', value: '2' },
      { text: 'Location3', value: '4' }
    ],
</code>```

},

```<code>methods: {

  handlePreview(){
    this.preview = true;
    this.selectedLocationText = this.selectedLocation.text
    console.log(this.selectedLocationText);
  },
</code>```

Is that easily possible to get the Text shown in my Preview? I just cant figure it out myself.

答:
I would do something like this:

```<code>this.selectedLocationText = this.options.find(option => option.value === this.selectedLocation)
</code>```

But remember to define selectedLocationText inside data()

Body:
I have a form built with bootstrap-vue. The form contains some Radio buttons. I do have a preview button which should show what was selected, but instead of the value from the radio button I would like the label. The radio button code looks something like this:

   Preview

My script looks something like below:

data() {
  return {
    selectedLocation: '1',

    options: [
      { text: 'Location1', value: '1' },
      { text: 'Location2', value: '2' },
      { text: 'Location3', value: '4' }
    ],

},

methods: {

  handlePreview(){
    this.preview = true;
    this.selectedLocationText = this.selectedLocation.text
    console.log(this.selectedLocationText);
  },

Is that easily possible to get the Text shown in my Preview? I just cant figure it out myself.

Body:
I would do something like this:

this.selectedLocationText = this.options.find(option => option.value === this.selectedLocation)

But remember to define selectedLocationText inside data()