问:
How to extract the headers of the individual search items using Selenium and Python
I am learning python and trying to paste the search results from python.org. I'm using Selenium.

Steps I want to do:

open python.org

Search for term "array" (Displays the results)

paste the list of search items (print("searchResults"))

My Code:

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")

#waiting to find the element before throwing error no element found
driver.implicitly_wait(10)
#driver.maximize_window()

#getting the website
driver.get("https://www.python.org/")
driver.implicitly_wait(5)
#finding element by id
driver.find_element_by_id("id-search-field").send_keys("arrays")
driver.find_element_by_id("submit").click()
print("Test Successful")

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
print(SearchResults.text)
</code>```

-> This pastes all results.

Now I want individual results items and their headers. When I inspect the searchresults on site, I get this: PEP 209 -- Multi-dimensional Arrays

There is no Tag, no Class and no Name to use.

How do I use this to just get all the headers?

答:
You could use selenium selector methods if you wanted.

Personally, i like to use Javascript and inject that and return the results.
For this example i would do this:

have a javascript file containing the following:

```<code>return (()=>{
   parsed_results = [];
   search_results=document.getElementsByClassName('list-recent-events')[0].children;
   for(var i =0;i<search_results.length;i++){
      result = search_results[i];
      text = result.innerText;
      title = result.getElementsByTagName('a')[0].innerText;
      href = 'https://www.python.org'+ result.getElementsByTagName('a')[0].getAttribute('href');
      parsed_results.push([title, text, href]);
   }
   return parsed_results;
  })();
</code>```

You can use it like this, after the page has loaded:

```<code>search_results = driver.execute_script(open('path/to/file.js').read())
</code>```

Then you can just go through them like you do normally in python.

```<code>for r in search_results:
    text = r[0]
    href = r[1]
    title = r[2]
</code>```

Body:
I am learning python and trying to paste the search results from python.org. I'm using Selenium.

Steps I want to do:

open python.org

Search for term "array" (Displays the results)

paste the list of search items (print("searchResults"))

My Code:

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")

#waiting to find the element before throwing error no element found
driver.implicitly_wait(10)
#driver.maximize_window()

#getting the website
driver.get("https://www.python.org/")
driver.implicitly_wait(5)
#finding element by id
driver.find_element_by_id("id-search-field").send_keys("arrays")
driver.find_element_by_id("submit").click()
print("Test Successful")

SearchResults = driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/section/form/ul")
print(SearchResults.text)

-> This pastes all results.

Now I want individual results items and their headers. When I inspect the searchresults on site, I get this: PEP 209 -- Multi-dimensional Arrays

There is no Tag, no Class and no Name to use.

How do I use this to just get all the headers?

Body:
You could use selenium selector methods if you wanted.

Personally, i like to use Javascript and inject that and return the results.
For this example i would do this:

have a javascript file containing the following:

return (()=>{
   parsed_results = [];
   search_results=document.getElementsByClassName('list-recent-events')[0].children;
   for(var i =0;i<search_results.length;i++){
      result = search_results[i];
      text = result.innerText;
      title = result.getElementsByTagName('a')[0].innerText;
      href = 'https://www.python.org'+ result.getElementsByTagName('a')[0].getAttribute('href');
      parsed_results.push([title, text, href]);
   }
   return parsed_results;
  })();

You can use it like this, after the page has loaded:

search_results = driver.execute_script(open('path/to/file.js').read())

Then you can just go through them like you do normally in python.

for r in search_results:
    text = r[0]
    href = r[1]
    title = r[2]


来源: stackexchange

问:
Import Python Classes to Javascript?
I want to use Python classes and functions I've written in a separate Javascript file. I'm wondering if it's possible to "import" those classes to my JS file?</p>

答:
Short answer: No, you can not do that. The problem is, that JavaScript runs on the client while python is server-sided.

Long answer: While you can't directly import python scripts and use their classes and functions in JavaScript, you can actually use server-sided JavaScript implementations like AJAX to call a Python script. This is not what you imagined however, such a request would look like this:

```<code>$.ajax({
  type: "POST",
  url: "~/your_script.py",
  data: { param1: value1}
}).done(function( o ) {
   // some more code
});
</code>```

As you can see, you are able to call a script and even pass some parameters, but that is about it. I mean in theorie sure, you could hack your way around and set up your website like this. But trust me, before you know what is happening you loose track of all the calls and the project becomes virtually impossible to maintain.

ContentLicense: CC BY-SA 4.0

Title: Import Python Classes to Javascript?

Body:
Short answer: No, you can not do that. The problem is, that JavaScript runs on the client while python is server-sided.

Long answer: While you can't directly import python scripts and use their classes and functions in JavaScript, you can actually use server-sided JavaScript implementations like AJAX to call a Python script. This is not what you imagined however, such a request would look like this:

$.ajax({
  type: "POST",
  url: "~/your_script.py",
  data: { param1: value1}
}).done(function( o ) {
   // some more code
});

As you can see, you are able to call a script and even pass some parameters, but that is about it. I mean in theorie sure, you could hack your way around and set up your website like this. But trust me, before you know what is happening you loose track of all the calls and the project becomes virtually impossible to maintain.


问:
Error: XHR failed loading: GET "http://localhost:8080/home" in agular
I am facing an issue while connecting the spring boot application with my angular application. I want to perform the get request from angular. For this, I made changes in my spring boot application by annotating the controller as @CrossOrigin.
    So far, I am able to hit the tomcat url from angular because logs in spring boot are publishing correctly. However, I am unable to fetch any response in my angular application. </p>

```<code>I believe it is related to type. For simplest type-String, I had tried but no help. I am getting the below error:

```XHR failed loading: GET "http://localhost:8080/home".```

Here is my spring boot:
```
@CrossOrigin
@RestController
public class HomeController {

    private CoronavirusDataService coronavirusDataService;

    @Autowired
    public  HomeController(CoronavirusDataService coronavirusDataService)
    {
        this.coronavirusDataService=coronavirusDataService;
    }
   @GetMapping("/home")
   public String home() throws IOException, InterruptedException, JSONException {
       String abc="Ria";
       List<LocationStats> locationStatsList= coronavirusDataService.fetchVirusData();
       //locationStatsList.stream().forEach(System.out:: println);
       //var myObj = JSON.parse('{"p": 5}');
       //return locationStatsList.toString();
       return abc;
   }
}```

Here is my angular:

```import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CoronaData} from '../model/corona-data';

@Component({
  selector: 'app-corona-module',
  templateUrl: './corona-module.component.html',
  styleUrls: ['./corona-module.component.css']
})
export class CoronaModuleComponent implements OnInit {

  coronaCount: CoronaData[] = [];
  coronaC: string;

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getAllCases();
    console.log(this.coronaCount);
  }
  public getAllCases(){
    const url = 'http://localhost:8080/home';
    this.http.get<string>(url).subscribe(
      res => {
        this.coronaC = res;
        console.log(this.coronaC);
      },
      error => {
        alert('An error has occured');
        console.log(this.coronaC);
      }
    );

  }

}```

I am quite struggling with basic, any help in this regard will be appreciated.

Thank you!
</code>```

答:
Modify my angular function with below changes:</p>

```<code> public getAllCases(){
    const url = 'http://localhost:8080/home';
    this.http.get(url, {responseType: 'text' }).subscribe(
      res => {
        this.coronaC = res;
        console.log(this.coronaC);
      },
      error => {
        alert('An error has occured');
        console.log(this.coronaC);
      }
    );

  }```
</code>```

Body:
I am facing an issue while connecting the spring boot application with my angular application. I want to perform the get request from angular. For this, I made changes in my spring boot application by annotating the controller as @CrossOrigin.
    So far, I am able to hit the tomcat url from angular because logs in spring boot are publishing correctly. However, I am unable to fetch any response in my angular application.

I believe it is related to type. For simplest type-String, I had tried but no help. I am getting the below error:

```XHR failed loading: GET "http://localhost:8080/home".```

Here is my spring boot:
```
@CrossOrigin
@RestController
public class HomeController {

    private CoronavirusDataService coronavirusDataService;

    @Autowired
    public  HomeController(CoronavirusDataService coronavirusDataService)
    {
        this.coronavirusDataService=coronavirusDataService;
    }
   @GetMapping("/home")
   public String home() throws IOException, InterruptedException, JSONException {
       String abc="Ria";
       List<LocationStats> locationStatsList= coronavirusDataService.fetchVirusData();
       //locationStatsList.stream().forEach(System.out:: println);
       //var myObj = JSON.parse('{"p": 5}');
       //return locationStatsList.toString();
       return abc;
   }
}```

Here is my angular:

```import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CoronaData} from '../model/corona-data';

@Component({
  selector: 'app-corona-module',
  templateUrl: './corona-module.component.html',
  styleUrls: ['./corona-module.component.css']
})
export class CoronaModuleComponent implements OnInit {

  coronaCount: CoronaData[] = [];
  coronaC: string;

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getAllCases();
    console.log(this.coronaCount);
  }
  public getAllCases(){
    const url = 'http://localhost:8080/home';
    this.http.get<string>(url).subscribe(
      res => {
        this.coronaC = res;
        console.log(this.coronaC);
      },
      error => {
        alert('An error has occured');
        console.log(this.coronaC);
      }
    );

  }

}```

I am quite struggling with basic, any help in this regard will be appreciated.

Thank you!

Body:
Modify my angular function with below changes:

 public getAllCases(){
    const url = 'http://localhost:8080/home';
    this.http.get(url, {responseType: 'text' }).subscribe(
      res => {
        this.coronaC = res;
        console.log(this.coronaC);
      },
      error => {
        alert('An error has occured');
        console.log(this.coronaC);
      }
    );

  }```


问:
Django admin not allowing superuser to log in (Custom User Model)
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below:

```<code>CustomUser.objects.all().values()
<QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]>
</code>```

I am officially puzzled as to what I have done incorrectly... Please help me figure this one out...

models.py:

```<code>from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.conf import settings

class UserType(models.Model):
    """
    This model defines the types of users which are allowed to be created in the application. Examples include:
    API Read Only User
    API Full CRUD User
    Business User
    """
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_updated_by')

class Role(models.Model):
    """
    This model defines the job code/organization role a particular user is related to within their organization.
    Examples include:
    System User
    Business User
    Business User Manager
    """
    name = models.CharField(max_length=50)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_updated_by')

class CustomBaseUserManager(BaseUserManager):
    """
    Defined a custom base user manager class so as operations are executed against the CustomUser model, application
    specific fields can be utilized.
    """

    def create_user(self, role, user_type, username=None, email=None, password=None):
        # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

        # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True)

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True)

        user = self.model(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, role, user_type, username=None, email=None, password=None):

    # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

    # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True).id

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True).id

        user = self.create_user(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.is_staff = True
        user.is_superuser = True
        user.is_active = True
        user.is_admin = True
        user.set_password(password)
        user.save(using=self._db)

        return user

class CustomUser(AbstractUser):
    """
    This is a custom user model allowing for the required relationship between a user and a specific role as defined
    by the organization. The only roles which will be allowed to be assigned to users are those which are active at the
    time the user is being created.
    """

    role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                             blank=False)
    user_type = models.ForeignKey(UserType, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                                  blank=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_updated_by')

    objects = CustomBaseUserManager()

    REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + [
        'role',
        'user_type'
    ]

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def __str__(self):
        return '{} <{}>'.format(self.get_full_name(), self.email)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True
</code>```

settings.py:

```<code>"""
Django settings for CategoryManager project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

SESSION_COOKIE_DOMAIN = '127.0.0.1:8000/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l%sn*03#ls^d6e5e-&)u93lyqzvh$bh1nij)ye2h4la$&jz^t!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CategoryManager.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CategoryManager.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Custom user definition
AUTH_USER_MODEL = 'Users.CustomUser'

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by custom User model, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
)

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
</code>```

SOLVED:
Turns out there was some issue in my local cache which was preventing django from being able to actually allow me to log in. Once I cleared my cache locally, I was able to log in.

答: SOLVED: Turns out there was some issue in my local cache which was preventing django from being able to actually allow me to log in. Once I cleared my cache locally, I was able to log in.</p>

Body:
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below:

CustomUser.objects.all().values()
<QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]>

I am officially puzzled as to what I have done incorrectly... Please help me figure this one out...

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.conf import settings

class UserType(models.Model):
    """
    This model defines the types of users which are allowed to be created in the application. Examples include:
    API Read Only User
    API Full CRUD User
    Business User
    """
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_updated_by')

class Role(models.Model):
    """
    This model defines the job code/organization role a particular user is related to within their organization.
    Examples include:
    System User
    Business User
    Business User Manager
    """
    name = models.CharField(max_length=50)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_updated_by')

class CustomBaseUserManager(BaseUserManager):
    """
    Defined a custom base user manager class so as operations are executed against the CustomUser model, application
    specific fields can be utilized.
    """

    def create_user(self, role, user_type, username=None, email=None, password=None):
        # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

        # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True)

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True)

        user = self.model(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, role, user_type, username=None, email=None, password=None):

    # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

    # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True).id

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True).id

        user = self.create_user(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.is_staff = True
        user.is_superuser = True
        user.is_active = True
        user.is_admin = True
        user.set_password(password)
        user.save(using=self._db)

        return user

class CustomUser(AbstractUser):
    """
    This is a custom user model allowing for the required relationship between a user and a specific role as defined
    by the organization. The only roles which will be allowed to be assigned to users are those which are active at the
    time the user is being created.
    """

    role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                             blank=False)
    user_type = models.ForeignKey(UserType, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                                  blank=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_updated_by')

    objects = CustomBaseUserManager()

    REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + [
        'role',
        'user_type'
    ]

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def __str__(self):
        return '{} <{}>'.format(self.get_full_name(), self.email)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

settings.py:

"""
Django settings for CategoryManager project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

SESSION_COOKIE_DOMAIN = '127.0.0.1:8000/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l%sn*03#ls^d6e5e-&)u93lyqzvh$bh1nij)ye2h4la$&jz^t!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CategoryManager.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CategoryManager.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Custom user definition
AUTH_USER_MODEL = 'Users.CustomUser'

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by custom User model, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
)

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

SOLVED:
Turns out there was some issue in my local cache which was preventing django from being able to actually allow me to log in. Once I cleared my cache locally, I was able to log in.


问:
PHP/MySQL Many-to-many relationship - the next step here
I'm new to advanced MySQL having only come across many-to-many relationships yesterday. I'm working on a project where users can join multiple projects and projects can accommodate multiple users.

My tables are:

Users - ID, name, email, password etc
Projects - ID, name, URL etc

Following advice from this site, I have set up a linking table with two foreign keys matched to the IDs of the above tables:

Users_Projects - Users_ID, Projects_ID

I understand the next step is something to do with joining, but how do I add a user to a table, or see who the members of a project are/what projects a particular user is a member of?

答:
I think you forgot an id (in users, create new fields 'projectid' on user table)</p>

```<code>ADD USER => INSERT INTO users (name,email,...) VALUES ('fred','redeyes@XX.com',...);
CHECK USER => SELECT name, email FROM USERS;
CHECK USER BY PROJECT ID => SELECT name, email FROM USERS, PROJECTS WHERE USERS.projectid = PROJECTS.id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you forgot an id (in users, create new fields 'projectid' on user table)

ADD USER => INSERT INTO users (name,email,...) VALUES ('fred','redeyes@XX.com',...);
CHECK USER => SELECT name, email FROM USERS;
CHECK USER BY PROJECT ID => SELECT name, email FROM USERS, PROJECTS WHERE USERS.projectid = PROJECTS.id


问:
Using R to filter through several different files
I am looking to create a function that searches a column for a specific value we'll say "ID". I was able to create a function that searches for one file, but I want it to keep going through and compile all records/observations where the filter is TRUE.

so far I have

```<code>ID_search <- function(ID_num){
                 DATA.1 %>% filter(ID == "ID_num")
}
</code>```

After it completes it's search in one file I want it to keep looking in the other files, say DATA.2, DATA.3 and so on and then eventually prints out every record/observation that it finds. It would be nice to also have it return that "No records found in Data.X" and then continue it's search and do this process until it's checked all files. I am fairly new to R, so still trying to figure stuff out. Any help or suggestions would be greatly appreciated!

答:
We'll illustrate the subsetting process with lapply() and the Pokémon Stats data, which consists of one comma separated values file for each of seven generations of Pokémon.

```<code>download.file("https://raw.githubusercontent.com/lgreski/pokemonData/master/pokemonData.zip",
              "pokemonData.zip",
              method="curl",mode="wb")
unzip("pokemonData.zip")
</code>```

Next, we read the list of data files to be processed, then use lapply() with an anonymous function and a second argument, y, to subset on the Type1 stat.

```<code>thePokemonFiles <- list.files("./pokemonData",pattern = ".csv",
                              full.names=TRUE)
pokemonDataFiles <- lapply(thePokemonFiles,function(x,y) {
     data <- read.csv(x,stringsAsFactors=FALSE)
     aSubset <- data[data$Type1 == y,]
     if (nrow(aSubset) == 0) message("No pokemon of type1 = ",y,
                                     " in ",x)
     else aSubset

},"Flying")
</code>```

The function writes messages for the files that have no Pokémon with Type1 of Flying.

```<code>No pokemon of type1 = Flying in ./pokemonData/gen01.csv
No pokemon of type1 = Flying in ./pokemonData/gen02.csv
No pokemon of type1 = Flying in ./pokemonData/gen03.csv
No pokemon of type1 = Flying in ./pokemonData/gen04.csv
No pokemon of type1 = Flying in ./pokemonData/gen07.csv
</code>```

Finally, we bind the data and print the first few rows of Pokémon whose Type1 stat is Flying.

```<code>data <- do.call(rbind,pokemonDataFiles)
head(data)
</code>```

...and the output:

```<code>head(data)
    Number                    Name  Type1  Type2 Total HP Attack Defense
150    641 TornadusIncarnate Forme Flying          580 79    115      70
151    641   TornadusTherian Forme Flying          580 79    100      80
73     714                  Noibat Flying Dragon   245 40     30      35
74     715                 Noivern Flying Dragon   535 85     70      80
    SpecialAtk SpecialDef Speed Generation Legendary
150        125         80   111          5      True
151        110         90   121          5      True
73          45         40    55          6     False
74          97         80   123          6     False
</code>```

Body:
I am looking to create a function that searches a column for a specific value we'll say "ID". I was able to create a function that searches for one file, but I want it to keep going through and compile all records/observations where the filter is TRUE.

so far I have

ID_search <- function(ID_num){
                 DATA.1 %>% filter(ID == "ID_num")
}

After it completes it's search in one file I want it to keep looking in the other files, say DATA.2, DATA.3 and so on and then eventually prints out every record/observation that it finds. It would be nice to also have it return that "No records found in Data.X" and then continue it's search and do this process until it's checked all files. I am fairly new to R, so still trying to figure stuff out. Any help or suggestions would be greatly appreciated!

Body:
We'll illustrate the subsetting process with lapply() and the Pokémon Stats data, which consists of one comma separated values file for each of seven generations of Pokémon.

download.file("https://raw.githubusercontent.com/lgreski/pokemonData/master/pokemonData.zip",
              "pokemonData.zip",
              method="curl",mode="wb")
unzip("pokemonData.zip")

Next, we read the list of data files to be processed, then use lapply() with an anonymous function and a second argument, y, to subset on the Type1 stat.

thePokemonFiles <- list.files("./pokemonData",pattern = ".csv",
                              full.names=TRUE)
pokemonDataFiles <- lapply(thePokemonFiles,function(x,y) {
     data <- read.csv(x,stringsAsFactors=FALSE)
     aSubset <- data[data$Type1 == y,]
     if (nrow(aSubset) == 0) message("No pokemon of type1 = ",y,
                                     " in ",x)
     else aSubset

},"Flying")

The function writes messages for the files that have no Pokémon with Type1 of Flying.

No pokemon of type1 = Flying in ./pokemonData/gen01.csv
No pokemon of type1 = Flying in ./pokemonData/gen02.csv
No pokemon of type1 = Flying in ./pokemonData/gen03.csv
No pokemon of type1 = Flying in ./pokemonData/gen04.csv
No pokemon of type1 = Flying in ./pokemonData/gen07.csv

Finally, we bind the data and print the first few rows of Pokémon whose Type1 stat is Flying.

data <- do.call(rbind,pokemonDataFiles)
head(data)

...and the output:

head(data)
    Number                    Name  Type1  Type2 Total HP Attack Defense
150    641 TornadusIncarnate Forme Flying          580 79    115      70
151    641   TornadusTherian Forme Flying          580 79    100      80
73     714                  Noibat Flying Dragon   245 40     30      35
74     715                 Noivern Flying Dragon   535 85     70      80
    SpecialAtk SpecialDef Speed Generation Legendary
150        125         80   111          5      True
151        110         90   121          5      True
73          45         40    55          6     False
74          97         80   123          6     False


问:
ReactiveUI WPF - Getting the last word of a textbox
I know this is a trivial program but I am Learning ReactiveUI and am new to the whole MVVN in the first place. I am trying to get the first and last name from a full name entered in a text box and show them in separate text blocks.

I got this working but my question is, is there a way to do the last name with just the LINQ style extensions or do I have to call another function using select(GetLast) as shown below? And, If there is a way to do it with LINQ style extensions, is it better to do it that way or with the select(GetLast)?

And if there's any other input you want to give, it would be appreciated.
Thank you in advance for any help given.

MainWindowViewModel.cs

private string _fullName;
public string FullName
{
    get => _fullName;
    set => this.RaiseAndSetIfChanged(ref _fullName, value);
}

private readonly ObservableAsPropertyHelper<string> _firstName;
public string FirstName => _firstName.Value;

private readonly ObservableAsPropertyHelper<string> _lastName;
public string LastName => _lastName.Value;

public MainWindowViewModel()
{
    _lastName = this.WhenAnyValue(x => x.FullName)
        .Select(full => full?.Trim())
        .DistinctUntilChanged()
        .Where(full => full != null)
        .Select(GetLast)                                   //<-- Point of question
        .ToProperty(this, x => x.LastName, out _lastName);

    _firstName = this.WhenAnyValue(x => x.FullName)
        .Select(full => full?.Trim())
        .DistinctUntilChanged()
        .Where(full => full != null)
        .Select(full => full.Split(' ')[0])
        .ToProperty(this, nameof(FirstName), out _firstName);
}

private string GetLast(string name)
{
    string[] splitName = name.Split(' ');
    if (splitName.Length > 2)
        return splitName[splitName.Length - 1];
    if (splitName.Length == 2)
        return splitName[1];
    return string.Empty;
}
```

<p><strong>MainWindow.xaml</strong></p>

```
<TextBlock Text="First Name:"
    Grid.Column="2" Grid.Row="2"
    FontWeight="SemiBold"
    Padding="5,5,0,5"/>
<TextBlock Text="Last Name:"
    Grid.Column="3" Grid.Row="2"
    FontWeight="SemiBold"
    Padding="5,5,0,5"/>

<TextBox x:Name="fullNameTextBox"
    Grid.Column="1" Grid.Row="3"
    MinWidth="150"/>
<TextBlock x:Name="firstNameTextBlock"
    Grid.Column="2" Grid.Row="3"
    MinWidth="75"
    Margin="5,0,0,0"/>
<TextBlock x:Name="lastNameTextBlock"
    Grid.Column="3" Grid.Row="3"
    MinWidth="75"
    Margin="5,0,0,0"/>
```

<p><strong>MainWindow.xaml.cs</strong></p>

<pre class="lang-cs prettyprint-override"><code>this.WhenActivated(disposableRegistration =>
{
    this.OneWayBind(ViewModel,
            vm => vm.FirstName,
            v => v.firstNameTextBlock.Text)
        .DisposeWith(disposableRegistration);

    this.OneWayBind(ViewModel,
            vm => vm.LastName,
            v => v.lastNameTextBlock.Text)
        .DisposeWith(disposableRegistration);

    this.Bind(ViewModel,
            vm => vm.FullName,
            v => v.fullNameTextBox.Text)
        .DisposeWith(disposableRegistration);
});
</code>```

答:
*UPDATED

how about

```<code>_lastName = this.WhenAnyValue(x => x.FullName)
.Select(full => full?.Trim())
.DistinctUntilChanged()
.Where(full => !string.IsNullOrWhitespace(full))
.Select(x => x.Split(' ').Last())
.ToProperty(this, x => x.LastName, out _lastName);
</code>```

As for "is this better", honestly, that's your call.  I think this is pretty straightforward - it's just linq - but it might be that your co-workers don't speak linq well and would prefer a a seperate method they can unit test and easily grasp.

Body:
I know this is a trivial program but I am Learning ReactiveUI and am new to the whole MVVN in the first place. I am trying to get the first and last name from a full name entered in a text box and show them in separate text blocks.

I got this working but my question is, is there a way to do the last name with just the LINQ style extensions or do I have to call another function using select(GetLast) as shown below? And, If there is a way to do it with LINQ style extensions, is it better to do it that way or with the select(GetLast)?

And if there's any other input you want to give, it would be appreciated.
Thank you in advance for any help given.

MainWindowViewModel.cs

private string _fullName;
public string FullName
{
    get => _fullName;
    set => this.RaiseAndSetIfChanged(ref _fullName, value);
}

private readonly ObservableAsPropertyHelper<string> _firstName;
public string FirstName => _firstName.Value;

private readonly ObservableAsPropertyHelper<string> _lastName;
public string LastName => _lastName.Value;

public MainWindowViewModel()
{
    _lastName = this.WhenAnyValue(x => x.FullName)
        .Select(full => full?.Trim())
        .DistinctUntilChanged()
        .Where(full => full != null)
        .Select(GetLast)                                   //<-- Point of question
        .ToProperty(this, x => x.LastName, out _lastName);

    _firstName = this.WhenAnyValue(x => x.FullName)
        .Select(full => full?.Trim())
        .DistinctUntilChanged()
        .Where(full => full != null)
        .Select(full => full.Split(' ')[0])
        .ToProperty(this, nameof(FirstName), out _firstName);
}

private string GetLast(string name)
{
    string[] splitName = name.Split(' ');
    if (splitName.Length > 2)
        return splitName[splitName.Length - 1];
    if (splitName.Length == 2)
        return splitName[1];
    return string.Empty;
}

MainWindow.xaml

<TextBlock Text="First Name:"
    Grid.Column="2" Grid.Row="2"
    FontWeight="SemiBold"
    Padding="5,5,0,5"/>
<TextBlock Text="Last Name:"
    Grid.Column="3" Grid.Row="2"
    FontWeight="SemiBold"
    Padding="5,5,0,5"/>

<TextBox x:Name="fullNameTextBox"
    Grid.Column="1" Grid.Row="3"
    MinWidth="150"/>
<TextBlock x:Name="firstNameTextBlock"
    Grid.Column="2" Grid.Row="3"
    MinWidth="75"
    Margin="5,0,0,0"/>
<TextBlock x:Name="lastNameTextBlock"
    Grid.Column="3" Grid.Row="3"
    MinWidth="75"
    Margin="5,0,0,0"/>

MainWindow.xaml.cs

this.WhenActivated(disposableRegistration =>
{
    this.OneWayBind(ViewModel,
            vm => vm.FirstName,
            v => v.firstNameTextBlock.Text)
        .DisposeWith(disposableRegistration);

    this.OneWayBind(ViewModel,
            vm => vm.LastName,
            v => v.lastNameTextBlock.Text)
        .DisposeWith(disposableRegistration);

    this.Bind(ViewModel,
            vm => vm.FullName,
            v => v.fullNameTextBox.Text)
        .DisposeWith(disposableRegistration);
});

Body:
*UPDATED

how about

_lastName = this.WhenAnyValue(x => x.FullName)
.Select(full => full?.Trim())
.DistinctUntilChanged()
.Where(full => !string.IsNullOrWhitespace(full))
.Select(x => x.Split(' ').Last())
.ToProperty(this, x => x.LastName, out _lastName);

As for "is this better", honestly, that's your call.  I think this is pretty straightforward - it's just linq - but it might be that your co-workers don't speak linq well and would prefer a a seperate method they can unit test and easily grasp.


问:
BGAppRefreshTask Background Task Not Executing
I am using the new iOS13 background task framework, with the implementation of a BGAppRefreshTask type. My problem is, my device is never calling the task, even after waiting several hours, but I am able to successfully run the code using the Debugger trick of calling _simulateLaunchForTaskWithIdentifier.

I have setup the following:

Enabled my app with the Background Modes capability, a checking the "Background fetch".

Added my background Id to Info.plist under "Permitted background task scheduler identifiers": "com.XYZ.PearWeather.backgroundAlerts".

I have registered the task from application(didFinishLaunchingWithOptions) in my AppDelegate:

```<code>        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.XYZ.PearWeather.backgroundAlerts", using: nil) { task in
            self.backgroundAlerts(task: task as! BGAppRefreshTask)
        }
</code>```

I am scheduling the task in a func within the AppDelegate, and calling it from my SceneDelegate sceneDidEnterBackground(). It was originally a static func, but I have now changed it to an instance func, and getting the AppDelegate instance (since I have tried many changes in desperation):

```<code>    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as! AppDelegate).scheduleBackgroundAlerts()
    }
</code>```

```<code>    func scheduleBackgroundAlerts() {
        let request = BGAppRefreshTaskRequest(identifier: "com.XYZ.PearWeather.backgroundAlerts")

        request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)

        do {
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: \(error)")
        }
    }
</code>```

At least in the Debugger scenario, there is no error in the submit call. I have tried many different values for the timeIntervalSinceNow parameter above. I am also calling this scheduleBackgroundAlerts() func from the task handler itself, which is as follows:

```<code>    func backgroundAlerts(task: BGAppRefreshTask) {

        scheduleBackgroundAlerts()

        task.expirationHandler = {
            // After all operations are cancelled, the completion block below is called to set the task to complete.
            task.setTaskCompleted(success: false)
        }

        AlertsOperation.showNotification()

        task.setTaskCompleted(success: true)
    }

</code>```

This implementation has changed a lot - I have originally used an OperationQueue, tried placing the scheduleBackgroundAlerts() call at the beginning and end of the func, etc. Now it is stripped down. The AlertOperation.showNotification() is also very simple now:

```<code>    static func showNotification() {

        let now = Date()
        let bg = Locale.currentLocale().formattedTime(date: now)
        SettingsManager.shared.settings.bg = bg
    }
</code>```

This is just storing a value in UserDefaults (in my SettingsManager, details of which are not relevant here) that I am able to read back in my app to see if anything happened.

Now, the original implementation of this func issues a local notification using UNUserNotificationCenter etc, which is what I am trying to do in this background task. This worked fine from the Debugger, but I reduced it to this simple code just to make a very small implementation.

As I say, calling the task handler from the Debugger works fine, using:

```<code>e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.XYZ.PearWeather.backgroundAlerts"]
</code>```

But nothing is happening from the device itself. I cannot see what I have missed. I do not know how to log any exception from within the background task handler either.

I am new to Swift and iOS, so any pointers appreciated. Most of the code above is almost a copy of the many tutorials on this subject. For me, though, things are not working and I have run out of options!

答:
Here is what I use.

In my AppDelegate, the iOS13 code.  Older style fetch not included:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate, UNUserNotificationCenterDelegate {
var backgroundSessionCompletionHandler: (() -> Void)?
var backgroundSynchTask: UIBackgroundTaskIdentifier = .invalid

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.WH.Air-Compare.WayneBGrefresh", using: nil) { task in
        self.handleAppRefresh(task: task as! BGAppRefreshTask)
        self.logSB.verbose("iOS 13  Registered for Background duty")
    }
} else {
    // Fallback on earlier versions
    self.logSB.verbose("iOS < 13  Registering for Background duty")
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
}
}

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler:@escaping () -> Void) {
let dateFormatter = DateFormatter()  // format the date for output
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.long
let convertedDate = dateFormatter.string(from: Date())
self.logSB.info("Background URLSession handled at \(convertedDate)")
self.logSB.info("Background URLSession ID \(identifier)")
let config = URLSessionConfiguration.background(withIdentifier: "WayneBGconfig")
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) -> Void in
    // yay! you have your tasks!
    self.logSB.info("Background completion handler here with \(downloadTasks.count) tasks")
    for i in 0...max(0,downloadTasks.count - 1) {
        let description: String = downloadTasks[i].taskDescription!
        self.logSB.info("Task ID \(i) is \(description)")
    }
}
backgroundSessionCompletionHandler = completionHandler
}

func applicationDidEnterBackground(_ application: UIApplication) {
if #available(iOS 13.0, *) {
    scheduleAppRefresh()
} else {
    // Fallback on earlier versions
}
}

@available(iOS 13.0, *)
func scheduleAppRefresh() {
logSB.info("Scheduling the AppRefresh in iOS 13 !!")
let request = BGAppRefreshTaskRequest(identifier: "com.WH.Air-Compare.WayneBGrefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60) // Fetch no earlier than 2 minutes from now

do {
    try BGTaskScheduler.shared.submit(request)
} catch {
    logSB.error("Could not schedule app refresh: \(error)")
}
}
</code>```

Body:
I am using the new iOS13 background task framework, with the implementation of a BGAppRefreshTask type. My problem is, my device is never calling the task, even after waiting several hours, but I am able to successfully run the code using the Debugger trick of calling _simulateLaunchForTaskWithIdentifier.

I have setup the following:

Enabled my app with the Background Modes capability, a checking the "Background fetch".

Added my background Id to Info.plist under "Permitted background task scheduler identifiers": "com.XYZ.PearWeather.backgroundAlerts".

I have registered the task from application(didFinishLaunchingWithOptions) in my AppDelegate:

        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.XYZ.PearWeather.backgroundAlerts", using: nil) { task in
            self.backgroundAlerts(task: task as! BGAppRefreshTask)
        }

I am scheduling the task in a func within the AppDelegate, and calling it from my SceneDelegate sceneDidEnterBackground(). It was originally a static func, but I have now changed it to an instance func, and getting the AppDelegate instance (since I have tried many changes in desperation):

    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as! AppDelegate).scheduleBackgroundAlerts()
    }

    func scheduleBackgroundAlerts() {
        let request = BGAppRefreshTaskRequest(identifier: "com.XYZ.PearWeather.backgroundAlerts")

        request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)

        do {
            try BGTaskScheduler.shared.submit(request)
        } catch {
            print("Could not schedule app refresh: \(error)")
        }
    }

At least in the Debugger scenario, there is no error in the submit call. I have tried many different values for the timeIntervalSinceNow parameter above. I am also calling this scheduleBackgroundAlerts() func from the task handler itself, which is as follows:

    func backgroundAlerts(task: BGAppRefreshTask) {

        scheduleBackgroundAlerts()

        task.expirationHandler = {
            // After all operations are cancelled, the completion block below is called to set the task to complete.
            task.setTaskCompleted(success: false)
        }

        AlertsOperation.showNotification()

        task.setTaskCompleted(success: true)
    }

This implementation has changed a lot - I have originally used an OperationQueue, tried placing the scheduleBackgroundAlerts() call at the beginning and end of the func, etc. Now it is stripped down. The AlertOperation.showNotification() is also very simple now:

    static func showNotification() {

        let now = Date()
        let bg = Locale.currentLocale().formattedTime(date: now)
        SettingsManager.shared.settings.bg = bg
    }

This is just storing a value in UserDefaults (in my SettingsManager, details of which are not relevant here) that I am able to read back in my app to see if anything happened.

Now, the original implementation of this func issues a local notification using UNUserNotificationCenter etc, which is what I am trying to do in this background task. This worked fine from the Debugger, but I reduced it to this simple code just to make a very small implementation.

As I say, calling the task handler from the Debugger works fine, using:

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.XYZ.PearWeather.backgroundAlerts"]

But nothing is happening from the device itself. I cannot see what I have missed. I do not know how to log any exception from within the background task handler either.

I am new to Swift and iOS, so any pointers appreciated. Most of the code above is almost a copy of the many tutorials on this subject. For me, though, things are not working and I have run out of options!

Body:
Here is what I use.

In my AppDelegate, the iOS13 code.  Older style fetch not included:

class AppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate, UNUserNotificationCenterDelegate {
var backgroundSessionCompletionHandler: (() -> Void)?
var backgroundSynchTask: UIBackgroundTaskIdentifier = .invalid

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.WH.Air-Compare.WayneBGrefresh", using: nil) { task in
        self.handleAppRefresh(task: task as! BGAppRefreshTask)
        self.logSB.verbose("iOS 13  Registered for Background duty")
    }
} else {
    // Fallback on earlier versions
    self.logSB.verbose("iOS < 13  Registering for Background duty")
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
}
}

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler:@escaping () -> Void) {
let dateFormatter = DateFormatter()  // format the date for output
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.long
let convertedDate = dateFormatter.string(from: Date())
self.logSB.info("Background URLSession handled at \(convertedDate)")
self.logSB.info("Background URLSession ID \(identifier)")
let config = URLSessionConfiguration.background(withIdentifier: "WayneBGconfig")
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) -> Void in
    // yay! you have your tasks!
    self.logSB.info("Background completion handler here with \(downloadTasks.count) tasks")
    for i in 0...max(0,downloadTasks.count - 1) {
        let description: String = downloadTasks[i].taskDescription!
        self.logSB.info("Task ID \(i) is \(description)")
    }
}
backgroundSessionCompletionHandler = completionHandler
}

func applicationDidEnterBackground(_ application: UIApplication) {
if #available(iOS 13.0, *) {
    scheduleAppRefresh()
} else {
    // Fallback on earlier versions
}
}

@available(iOS 13.0, *)
func scheduleAppRefresh() {
logSB.info("Scheduling the AppRefresh in iOS 13 !!")
let request = BGAppRefreshTaskRequest(identifier: "com.WH.Air-Compare.WayneBGrefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60) // Fetch no earlier than 2 minutes from now

do {
    try BGTaskScheduler.shared.submit(request)
} catch {
    logSB.error("Could not schedule app refresh: \(error)")
}
}


问:
Build a pipeline in azure data factory to load Excel files, format content, transform in csv and send to azure sql DB
I'm approaching to Azure environment and watching tutorials/reading documents, but I'm trying to figure out how to setup a flow that enables the process that I will describe hereunder. The starting point are reports in .xlsx format produced monthly by Mktg Dept: the requirements are to bring them in Azure SQL DB so that data can be stored and analysed. Sofar I managed to put those files (previously manually converted in .csv format) in a BLOB storage and build an ADF pipeline that copy each file in a table on the SQL DB.
The problem is that as far as I understood with ADF it's not possible to directly manage xlsx files, and I'm wondering how to set up an automated procedure that enables the conversion from .xlsx to .csv and save them on BLOB storage. I was thinking about adding to the pipeline a python script/Databricks notebook to convert format, but I'm not sure this could be the best solution. Any hint/reference to existing tutorial or resources would be very appreciated </p>

答:
I found a tutorial which uses Logic Apps to do the conversion.

Datanovice indirectly suggested using a Custom activity to run either a C# or Python application to do the conversion for you.

The least expensive solution would be to do the conversion before uploading to blob, like Datanovice said.


问:
mysql sum values from query
The mysql query looks like:

```<code>SELECT count(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id
</code>```

The result of that query:

```<code>   total | fname  |
  ------------------
    2    |  john
    3    |  mike
    5    |  july
</code>```

How can I sum values from column "total" using this mysql query?

答:
Use SUM on the subquery:

```<code>SELECT SUM(c.total) AS total_sum
FROM (
    SELECT count(f.id) as total, m1.fname
    FROM
        members m1 INNER JOIN
        new f ON m1.id = f.id
) AS c
</code>```

Title: mysql sum values from query

Body:
The mysql query looks like:

SELECT count(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id

The result of that query:

   total | fname  |
  ------------------
    2    |  john
    3    |  mike
    5    |  july

How can I sum values from column "total" using this mysql query?

Body:
Use SUM on the subquery:

SELECT SUM(c.total) AS total_sum
FROM (
    SELECT count(f.id) as total, m1.fname
    FROM
        members m1 INNER JOIN
        new f ON m1.id = f.id
) AS c


问:
Function returns wrong value for certain arrays
I have recently started coding and was working on a function that returns the 3 largest numbers in a given array. The function works for most arrays, but not for others. Below is the code:

```<code>def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist
</code>```

For instance, when I input the array [1,2,3,4,5] the function returns [3,4,5]. However, when I input [55, 43, 11, 3, -3, 10], the function returns 4 values: [10, 11, 43, 55].

Why is this?

Thank you so much!

答:
This nested loop can add an arbitrarily large number of elements to list (which is btw a bad name for a list because it overwrites the builtin function list()):

```<code>    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
</code>```

You only check the length of list in the outer loop, but the inner loop goes over the entire array and will potentially add all of them to list (if the array is in reverse-sorted order) before the condition is checked again.

A much simpler way to write this function would be to simply sort it and take the highest three elements:

```<code>from typing import List

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    return sorted(array)[-3:]
</code>```

(edit) A slightly more complex version that doesn't involve a sort:

```<code>def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    largest_3: List[int] = []
    for num in array:
        largest_3.append(num)
        if len(largest_3) > 3:
            largest_3.remove(min(largest_3))
    return largest_3
</code>```

In this implementation, largest_3 is never permitted to grow beyond 3 elements because every time it grows to 4, we remove exactly one element before we add any more.

Body:
I have recently started coding and was working on a function that returns the 3 largest numbers in a given array. The function works for most arrays, but not for others. Below is the code:

def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist

For instance, when I input the array [1,2,3,4,5] the function returns [3,4,5]. However, when I input [55, 43, 11, 3, -3, 10], the function returns 4 values: [10, 11, 43, 55].

Why is this?

Thank you so much!

Body:
This nested loop can add an arbitrarily large number of elements to list (which is btw a bad name for a list because it overwrites the builtin function list()):

    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)

You only check the length of list in the outer loop, but the inner loop goes over the entire array and will potentially add all of them to list (if the array is in reverse-sorted order) before the condition is checked again.

A much simpler way to write this function would be to simply sort it and take the highest three elements:

from typing import List

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    return sorted(array)[-3:]

(edit) A slightly more complex version that doesn't involve a sort:

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    largest_3: List[int] = []
    for num in array:
        largest_3.append(num)
        if len(largest_3) > 3:
            largest_3.remove(min(largest_3))
    return largest_3

In this implementation, largest_3 is never permitted to grow beyond 3 elements because every time it grows to 4, we remove exactly one element before we add any more.


问:
How to read CIFAR-10 dataset in Tensorflow?
Can anyone give a clean code to load CIFAR-10 in tensoflow?

I have checked the examples given in the tensorflow's github repo. But I do not want to resize the images to 24x24. Basically, I am looking for a easier and simpler code.

答: Note that there is now a built-in function to load this dataset.</p>


问:
Two variables in for loop in bash
```<code>for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        echo $file
    fi
done
</code>```

in this code, as you see i try to get the files in the /root folder the output should be like this:

```<code>/root/02
/root/03
/root/04
/root/05
etc....
</code>```

then i will use the output with commands

i have txt file, let's say the content like this:

```<code>first line
second line
third line
</code>```

i need read the txt file lines with the output from the code above in the same for loop, for example in the code echo $file i need change it to echo $file $line $line = the lines in the txt file

i found someone asked for something like my question and other in stackoverflow: https://www.unix.com/shell-programming-and-scripting/75414-sh-two-variables-loop.html

but all these, will not help me, because there are specific thing i need it!

what is the problem with their codes?

the problem is the out put will be like this:

the out put + the txt file

```<code>/root/02 first line
/root/03 second line
/root/04 third line
/root/05
/root/06
</code>```

i need if the output lines more than the lines in the txt file return to the first line in the txt file for example:

```<code>/root/02 first line
/root/03 second line
/root/04 third line
/root/05 first line
/root/06 second line
</code>```

Thanks.

答:
Put the lines of the file in an array. Then you can index the array with wraparound.</p>

```<code>readarray -t lines < filename.txt
i=0
for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        printf "%s %s\n" "$file" "${lines[$i]}"
        i=$(((i + 1) % "${#lines[@]}")) # increment i and wrap around to 0
    fi
done
</code>```

Title: Two variables in for loop in bash

Body:
for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        echo $file
    fi
done

in this code, as you see i try to get the files in the /root folder the output should be like this:

/root/02
/root/03
/root/04
/root/05
etc....

then i will use the output with commands

i have txt file, let's say the content like this:

first line
second line
third line

i need read the txt file lines with the output from the code above in the same for loop, for example in the code echo $file i need change it to echo $file $line $line = the lines in the txt file

i found someone asked for something like my question and other in stackoverflow: https://www.unix.com/shell-programming-and-scripting/75414-sh-two-variables-loop.html

but all these, will not help me, because there are specific thing i need it!

what is the problem with their codes?

the problem is the out put will be like this:

the out put + the txt file

/root/02 first line
/root/03 second line
/root/04 third line
/root/05
/root/06

i need if the output lines more than the lines in the txt file return to the first line in the txt file for example:

/root/02 first line
/root/03 second line
/root/04 third line
/root/05 first line
/root/06 second line

Thanks.

Body:
Put the lines of the file in an array. Then you can index the array with wraparound.

readarray -t lines < filename.txt
i=0
for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        printf "%s %s\n" "$file" "${lines[$i]}"
        i=$(((i + 1) % "${#lines[@]}")) # increment i and wrap around to 0
    fi
done


问:
Pure Java alternative to database / cache for storing records
I have created an application sold to customers, some of which are hardware manufacturers with fixed constraints (slow CPU). The app has to be in java, so that it can be easily installed as a single package.

The application is multithreaded and maintains audio records. In this particular case all we have is INSERT SOMEDATA FOR RECORD, each record representing an audio file (and this can be done by different threads), and then later on we have SELECT SOMEDATA WHERE IDS in (x, y, z) by an single thread, then 3rd step is we actually DELETE all the data in this table.

The main constraint is cpu, slow single cpu. Memory is also a constraint, but only in that the application is designed so it can process an unlimited number of files, and so even if had lots of memory would eventually run out if all stored in memory rather than utilizing the disk.

In my Java application I started off using the H2 database to store all my data. But the software has to run on some slow single cpu servers so I want to reduce the cpu cycles used, and one area I want to look again is the database.

In many cases I am inserting data into database simply for the purposes of keeping the data off the heap otherwise would run out of memory, then later on we retrieve the data, we never have to UPDATE the data.

So I considered using a cache like ehCache but that has two problems:

It doesn't guarantee the data will not be thrown away (If the cache gets full)

I can only retrieve records one at a time, whereas with relational database I can retrieve a batch of records, this looks like a potential bottleneck.

What is an alternative that solves these issues ?

答:
You want to retrieve records in batch fast, not loose any data, but you don't need optimized queries nor updates and you want to use CPU and memory resources as effectively as possible:

Why don't you simply store your records in a file? The operating system uses any free memory for caching. So when you access your file frequently, the OS will do its best to keep as much content as possible in memory. The OS does this job anyway, so this type of  caching costs you no additional CPU and no single line of code.

The only scenarios where it could make sense to invest more in optimization would be:

a) Your process or other processes make heavy use of the file system and
pollute file cache

b) Serialization / deserialization is too expensive

In case of a):

Define your priorities. An explicit cache (in heap or off-heap) can help you to keep some content of selected files in memory. But this memory will not be avalaible anymore for the OS's file cache. So while you speed up one file access you potentially slow down access to other files.

In case of b):

Measure performance first, before you optimize anything. Usually disk access is the bottleneck - that's something you cannot change without replacing hardware. If you still want to optimize (e.g. because GC eats up CPU due to a very high number of temporarily created objects - i guess with only one core serial GC will be in use) then I suggest to have a closer look on Google flatbuffers.

You started with the most complex solution for your problem, a database. I suggest to start at the other end of the spectrum and keep it as simple as possible

UPDATE:
The question has been edited in the meanwhile and requirements have changed. A new requirement is now that it has to be possible to read selected records by IDs.

Possible extensions:

Store each record in an own file and use the key as file name

Store all records in one file and use a file-based HashMap implementation
like MapDB's HTreeMap implementation.

Independent from the chosen extension, the operating system's file cache will do its best to hold as much content as possible in main memory.


问:
Converting single column of dictionary like text to multiple columns with key as column name using Pandas
I have the following data to parse,

```<code>                                                                                Data
0    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
1    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
2    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
3    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
4    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
</code>```

Required to be converted to,

```<code>     key0      key1      key2      keyn
0    rand_val  rand_val  rand_val  rand_val
1    rand_val  rand_val  rand_val  rand_val
2    rand_val  rand_val  rand_val  rand_val
3    rand_val  rand_val  rand_val  rand_val
4    rand_val  rand_val  rand_val  rand_val
</code>```

I was able to extract the keys and convert them to column labels the hard way but kind of stuck in getting the final outcome

```<code>attr_data = data.loc[:, ['Data']]
print attr_data.iloc[0]
new_attr1 = pd.DataFrame(attr_data.Data.str.replace('{', ''))
new_attr2 = pd.DataFrame(new_attr1.Data.str.replace('}', ''))
new_attr3 = pd.DataFrame(new_attr2.Data.str.replace('"', ''))
new_attr4 = pd.DataFrame(new_attr3.Data.str.split(','))

print new_attr4.iloc[0]
column_names = []
for label, content in new_attr4.iloc[0].items():
    print label
    for item in content:
        column_names.append(item.split(':')[0])

print column_names
</code>```

答:
We can do with dataframe

```<code>yourdf=pd.DataFrame(df.Data.tolist())
</code>```

Body:
I have the following data to parse,

                                                                                Data
0    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
1    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
2    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
3    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}
4    {"key0":"rand_val","key1":"rand_val","key2":"rand_val", ..., "keyn":"rand_val_n"}

Required to be converted to,

     key0      key1      key2      keyn
0    rand_val  rand_val  rand_val  rand_val
1    rand_val  rand_val  rand_val  rand_val
2    rand_val  rand_val  rand_val  rand_val
3    rand_val  rand_val  rand_val  rand_val
4    rand_val  rand_val  rand_val  rand_val

I was able to extract the keys and convert them to column labels the hard way but kind of stuck in getting the final outcome

attr_data = data.loc[:, ['Data']]
print attr_data.iloc[0]
new_attr1 = pd.DataFrame(attr_data.Data.str.replace('{', ''))
new_attr2 = pd.DataFrame(new_attr1.Data.str.replace('}', ''))
new_attr3 = pd.DataFrame(new_attr2.Data.str.replace('"', ''))
new_attr4 = pd.DataFrame(new_attr3.Data.str.split(','))

print new_attr4.iloc[0]
column_names = []
for label, content in new_attr4.iloc[0].items():
    print label
    for item in content:
        column_names.append(item.split(':')[0])

print column_names

Body:
We can do with dataframe

yourdf=pd.DataFrame(df.Data.tolist())


问:
How to add a proptype of a setState method
I'm creating a reusable component for a project that I have.
This component has a user and a setUser as props like the example bellow.

```<code>const UserComponent = ({ user, setUser }) => {

     const calcHandler = useCallback(() => {
        setUser(prevUser => {
             // ...some calculation
             return userCopy;
         });
     }, [setUser]);

     return (
         <div>
             ... some content
         </div>
     );
 };
</code>```

As you can see this component has a method to calculate some operations called calcHandler, and there is only one dependency.

This is the proptype validation:

```<code> UserComponent.propTypes = {
    user: PropTypes.shape({
        // some props
    }).isRequired,
    setUser: PropTypes.func.isRequired,
};
</code>```

However, for the prop setUser it is mandatory to be like a setState method (one from the useState hook). Because I can get the previeous value from it and prevent to add other dependency to the useCallback.

```<code>setUser(prevUser => //... some calculation);
</code>```

I need to improve the validation of the prop setUser. It isn't just a function.
Does anyone know how to do it?

答:
However, for the prop setUser it is mandatory to be like a setState
  method (one from the useState hook). Because I can get the previeous
  value from it and prevent to add other dependency to the useCallback.

That sounds like you are looking for PropTypes.shape but for a function

Unfortunately there isn't such thing and the only alternative is custom validator

Additionally you have to find a way to get function parameters and its return value as its required for validation.

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

TaskManagerFollowUp.propTypes = {
  setUser: function(props, propName, componentName) {
    const prop = props[propName];

    if(!getParamNames(prop).length) { // doesnt take any param
      throw new Error('invalid function propType')
    }

  }
}
```

Body:
I'm creating a reusable component for a project that I have.
This component has a user and a setUser as props like the example bellow.

const UserComponent = ({ user, setUser }) => {

     const calcHandler = useCallback(() => {
        setUser(prevUser => {
             // ...some calculation
             return userCopy;
         });
     }, [setUser]);

     return (

             ... some content

     );
 };

As you can see this component has a method to calculate some operations called calcHandler, and there is only one dependency.

This is the proptype validation:

 UserComponent.propTypes = {
    user: PropTypes.shape({
        // some props
    }).isRequired,
    setUser: PropTypes.func.isRequired,
};

However, for the prop setUser it is mandatory to be like a setState method (one from the useState hook). Because I can get the previeous value from it and prevent to add other dependency to the useCallback.

setUser(prevUser => //... some calculation);

I need to improve the validation of the prop setUser. It isn't just a function.
Does anyone know how to do it?


问:
How to use GNUPlot with dataset that is single-row separated with a comma
How can I use GNUplot with a single row dataset separated with commas and no spaces?

Example:

36.9,39.4,40.7,45.9,48.4,49.3,

答:
```<code>$ROWDATA << EOD
 36.9,39.4,40.7,45.9,48.4,49.3,
EOD

set datafile separator comma
row = 0
set yrange [0:50]
plot $ROWDATA matrix using 1:0 every :::row::row with points pt 7
</code>```

Yes this is a really obscure command. Note that the program will interpret the trailing comma as an empty field and issue a non-fatal error message about missing matrix elements.

Body:
$ROWDATA << EOD
 36.9,39.4,40.7,45.9,48.4,49.3,
EOD

set datafile separator comma
row = 0
set yrange [0:50]
plot $ROWDATA matrix using 1:0 every :::row::row with points pt 7

Yes this is a really obscure command. Note that the program will interpret the trailing comma as an empty field and issue a non-fatal error message about missing matrix elements.


问:
Is there a way to remove the site nav from a single page in BigCommerce?
I am creating a landing page where I do not want any navigation and it is injecting the site header HTML. Is there a way to make a landing page without any navigation in BigCommerce? I am using the Corner Stone them.</p>

答:
Your best bet is to duplicate the templates/layout/base.html file, remove the header from there, then create a new custom template in templates/custom/page/ which then references the new layout that doesn't include the header.

You can then assign your page to that new template.


问:
Is there a Windows alternative to Mainframe FileAID?
For work, I'm on a team that is migrating a system from Mainframe to AWS.  Part of the work I do is using FileAID to work on fixed-width files with custom layouts (here, if anyone is curious)  What I'm wondering is, is there any sort of a desktop application that has similar file layout display features similar to FileAID?</p>

答:
Two Optioms

Microfocus Cobol has an editor

RecordEditor can display fixed width file.

RecordEditor

The RecordEditor can display Binary Mainframe or PC / Linux text files.

For File Description the RecordEditor can:

Use File Descriptions entered into it

Imported Cobol Copybooks

Cobol Copybooks directly (Single Record File types)

Xml File Descriptions

Entering filename and Cobol Copybook:

File Display:

Record Display:

Note: When first starting the RecordEditor make sure you select the schema and also the Cobol option

Related question

Binary Mainframe Cobol Files

RecordEditor Layout Wizard