问:
JAXB Error : has more than one mapping. Due to two Object Factories with the same Bean
I have two Maven JAXB Projects.

A: Main Maven JAXB stubs XSD project, this contains BASKET.xsd

B: Maven JAXB stubs User-Project that wants to wrap BASKET.xsd in their own Objects.

This results in TWO Objects factories (different packages), both declare the following...

```<code>@XmlElementDecl(namespace = "http://www.bob.org/bob/namespace/", name = "Basket")
public JAXBElement<BasketType> createBasket(BasketType value) {
    return new JAXBElement<BasketType>(QNAME, BasketType.class, null, value);
}
</code>```

This generation is done via this plugin...
                org.jvnet.jaxb2.maven2
                maven-jaxb2-plugin
                0.13.2

On application start I get CXF-RT-Frotnend-JaxRS 3.1.11 giving me an error...

```<code>017-07-03 14:38:54,613845801: WARN  : [RMI TCP Connection(3)-127.0.0.1] [] org.apache.cxf.jaxrs.utils.ResourceUtils: No JAXB context can be created
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
The element name {http://www.bob.org/bob/namespace/}Basket has more than one mapping.
    this problem is related to the following location:
        at public javax.xml.bind.JAXBElement com.bob.bean.ObjectFactory.createBasket(org.bob.BasketType)
        at com.bob.bean.ObjectFactory
    this problem is related to the following location:
        at public javax.xml.bind.JAXBElement org.userservice.bean.ObjectFactory.createBasket(org.bob.BasketType)
</code>```

This wasn't an error I got untill I upgraded from CXF 2.7.7 to 3.1.11

Does anyone know if there is a way to get maven-jaxb2-plugin to not generate the method createBasket(..) on the UserService ObjectFactory??

Or to get CXF to accept the two methods, which are identical, on the two ObjectFactoty classes?

答:
Like your project, mine had 2 packages containing the same class with same element name and namespace. From what I got, that confuses the marshalling process, as JAXB can't tell exactly which mapping it should use to parse between XML and Java object.

As you can see, the runtime error is quite similar:

```<code>The element name {http://schemas.foobar.com/2021/12/01/ws/platform/coretypes}Identifiers has more than one mapping.
        this problem is related to the following location:
                at public javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory.createIdentifiers(myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Identifiers)
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory
                at protected javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding.nameOther
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding
                at protected myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ClinicianRole.clinicianRoleType
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ClinicianRole
                at protected java.util.List myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole.clinicianRole
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole
                at public myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ObjectFactory.createArrayOfClinicianRole()
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ObjectFactory
        this problem is related to the following location:
                at public javax.xml.bind.JAXBElement myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory.createIdentifiers(myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Identifiers)
                at myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory
                at protected javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink.appointmentIdentifier
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink
                at public javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.ObjectFactory.createAppointmentLink(myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink)
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.ObjectFactory
</code>```

My solution though was slightly different. The classes were being generated by the wsimport tool, so I provided a binding file with generateElementProperty="false" to force the tool to ditch JAXBElement generics in the code, which impacts how the mappings are generated.

My binding file ended up looking like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings jaxb:version="2.0"
  xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" jaxb:extensionBindingPrefixes="xjc">
  <jaxb:globalBindings generateElementProperty="false"/>
</jaxb:bindings>
```
<p>...so I could call <code>wsimport</code> with this command in my shell:</p>
```path-to-your-jdk/bin/wsimport -verbose -extension -keep -Xnocompile -d your-target-dir your-schema.xml -b your-binding-file.xjb
```

That replaced JAXBElement<SomeType> with SomeType in all generated classes, and the error was gone.

Body:
I have two Maven JAXB Projects.

A: Main Maven JAXB stubs XSD project, this contains BASKET.xsd

B: Maven JAXB stubs User-Project that wants to wrap BASKET.xsd in their own Objects.

This results in TWO Objects factories (different packages), both declare the following...

@XmlElementDecl(namespace = "http://www.bob.org/bob/namespace/", name = "Basket")
public JAXBElement<BasketType> createBasket(BasketType value) {
    return new JAXBElement<BasketType>(QNAME, BasketType.class, null, value);
}

This generation is done via this plugin...
                org.jvnet.jaxb2.maven2
                maven-jaxb2-plugin
                0.13.2

On application start I get CXF-RT-Frotnend-JaxRS 3.1.11 giving me an error...

017-07-03 14:38:54,613845801: WARN  : [RMI TCP Connection(3)-127.0.0.1] [] org.apache.cxf.jaxrs.utils.ResourceUtils: No JAXB context can be created
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
The element name {http://www.bob.org/bob/namespace/}Basket has more than one mapping.
    this problem is related to the following location:
        at public javax.xml.bind.JAXBElement com.bob.bean.ObjectFactory.createBasket(org.bob.BasketType)
        at com.bob.bean.ObjectFactory
    this problem is related to the following location:
        at public javax.xml.bind.JAXBElement org.userservice.bean.ObjectFactory.createBasket(org.bob.BasketType)

This wasn't an error I got untill I upgraded from CXF 2.7.7 to 3.1.11

Does anyone know if there is a way to get maven-jaxb2-plugin to not generate the method createBasket(..) on the UserService ObjectFactory??

Or to get CXF to accept the two methods, which are identical, on the two ObjectFactoty classes?

Body:
Like your project, mine had 2 packages containing the same class with same element name and namespace. From what I got, that confuses the marshalling process, as JAXB can't tell exactly which mapping it should use to parse between XML and Java object.

As you can see, the runtime error is quite similar:

The element name {http://schemas.foobar.com/2021/12/01/ws/platform/coretypes}Identifiers has more than one mapping.
        this problem is related to the following location:
                at public javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory.createIdentifiers(myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Identifiers)
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory
                at protected javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding.nameOther
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding
                at protected myapp.visit.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Coding myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ClinicianRole.clinicianRoleType
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ClinicianRole
                at protected java.util.List myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole.clinicianRole
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole
                at public myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ArrayOfClinicianRole myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ObjectFactory.createArrayOfClinicianRole()
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.clinician.ObjectFactory
        this problem is related to the following location:
                at public javax.xml.bind.JAXBElement myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory.createIdentifiers(myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.Identifiers)
                at myapp.appointment.com.foobar.schemas._2021._12._01.ws.platform.coretypes.ObjectFactory
                at protected javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink.appointmentIdentifier
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink
                at public javax.xml.bind.JAXBElement myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.ObjectFactory.createAppointmentLink(myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.AppointmentLink)
                at myapp.visit.com.foobar.schemas._2021._12._01.ws.pas.appointment.ObjectFactory

My solution though was slightly different. The classes were being generated by the wsimport tool, so I provided a binding file with generateElementProperty="false" to force the tool to ditch JAXBElement generics in the code, which impacts how the mappings are generated.

My binding file ended up looking like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings jaxb:version="2.0"
  xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" jaxb:extensionBindingPrefixes="xjc">
  <jaxb:globalBindings generateElementProperty="false"/>
</jaxb:bindings>

...so I could call wsimport with this command in my shell:

path-to-your-jdk/bin/wsimport -verbose -extension -keep -Xnocompile -d your-target-dir your-schema.xml -b your-binding-file.xjb

That replaced JAXBElement<SomeType> with SomeType in all generated classes, and the error was gone.


来源: stackexchange

问:
How to run multi parameter function with if, elif and else?
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.</p>
```<code>def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)
</code>```

答:
Your code won't work, since the variables you are trying to update from inside your function, are not in the scope of that function/are not defined for the function.

But you should ask yourself what you want to accomplish with your code.

It seems like you want to know what option the user has chosen, and you want to make sure it is only one of these you asked for.

You can use the following code, to get the user input, if it macthes your question options, or you will get No food found.

def user_likes_that_food(food, foods):
    if food.lower() in foods:
        return food
    else:
        return "No food found"

print("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")

user_input = input("I like ")

user_likes = user_likes_that_food(
    user_input, ("italian", "chinese", "japanese", "mexican"))

print(user_likes)
```

ContentLicense: CC BY-SA 4.0

Body:
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.

def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)


问:
How can I get group members from an AD group that only contains security groups?
I have 3 groups (HR, COMPT and FIN) and their groups contains only security groups.
How do I extract their members of their groups?</p>
```<code>$Groups =
@"
GroupNames;
HR
COMPT
FIN
"@ | ConvertFrom-Csv -Delimiter ';'

#HR has 3 security groups
#COMPT has 5 security groups
#FIN has 2 security groups
### I want to know how can I get their members ###

foreach ($Group in $Groups){
#Save-File to this Path
$Path = "C:\Temp\"

$group.GroupNames | Get-ADGroupMember | select name -ExpandProperty Name | ForEach-Object {
Get-ADGroup $_ -Properties Members | select Name |
#Export CSV
Export-Csv -Path (Join-Path -Path $path -ChildPath ('{0}.csv' -f $group.Name)) -NoTypeInformation -Delimiter ";" -Encoding UTF8

  }
}
</code>```

答:
You can try something like this, first you loop through the groups on the CSV (Parents), then for each parent you query their Member attribute (Child Groups) and for each child you query their Member attribute which should be in this case users objects. This would give you a report of each Parent Group and their Child Groups and their Members.

```<code># CSV Should have a `GroupNames` column!!
$groups = Import-Csv /path/to/parentGroups.csv

$result = foreach($parent in $groups.GroupNames) {
    $parentGroup = Get-ADGroup $parent -Properties Member
    foreach($child in $parentGroup.Member) {
        # NOTE: This assumes the Members of Parent are GROUPS!
        $childGroup = Get-ADGroup $child -Properties Member
        foreach($member in $childGroup.Member) {
            $member = Get-ADObject $member
            [pscustomobject]@{
                ParentGroup = $parentGroup.SamAccountName
                ChildGroup  = $childGroup.SamAccountName
                Member      = $member.SamAccountName
                ObjectClass = $member.ObjectClass
            }
        }
    }
}

$result | Export-Csv ..... -NoTypeInformation
</code>```

Body:
I have 3 groups (HR, COMPT and FIN) and their groups contains only security groups.
How do I extract their members of their groups?

$Groups =
@"
GroupNames;
HR
COMPT
FIN
"@ | ConvertFrom-Csv -Delimiter ';'

#HR has 3 security groups
#COMPT has 5 security groups
#FIN has 2 security groups
### I want to know how can I get their members ###

foreach ($Group in $Groups){
#Save-File to this Path
$Path = "C:\Temp\"

$group.GroupNames | Get-ADGroupMember | select name -ExpandProperty Name | ForEach-Object {
Get-ADGroup $_ -Properties Members | select Name |
#Export CSV
Export-Csv -Path (Join-Path -Path $path -ChildPath ('{0}.csv' -f $group.Name)) -NoTypeInformation -Delimiter ";" -Encoding UTF8

  }
}

Body:
You can try something like this, first you loop through the groups on the CSV (Parents), then for each parent you query their Member attribute (Child Groups) and for each child you query their Member attribute which should be in this case users objects. This would give you a report of each Parent Group and their Child Groups and their Members.

# CSV Should have a `GroupNames` column!!
$groups = Import-Csv /path/to/parentGroups.csv

$result = foreach($parent in $groups.GroupNames) {
    $parentGroup = Get-ADGroup $parent -Properties Member
    foreach($child in $parentGroup.Member) {
        # NOTE: This assumes the Members of Parent are GROUPS!
        $childGroup = Get-ADGroup $child -Properties Member
        foreach($member in $childGroup.Member) {
            $member = Get-ADObject $member
            [pscustomobject]@{
                ParentGroup = $parentGroup.SamAccountName
                ChildGroup  = $childGroup.SamAccountName
                Member      = $member.SamAccountName
                ObjectClass = $member.ObjectClass
            }
        }
    }
}

$result | Export-Csv ..... -NoTypeInformation


问:
Unit Testing with quarkus-smallrye-graphql
In a quarkus project with quarkus-smallrye-graphql lib, is there a way to unit test a GraphQL resource object like this one :

```<code>@GraphQLApi
public class ProductResource {

    @Inject
    private ProductRepository productRepository;

    @Query("products")
    @Description("Get all Products")
    @RolesAllowed({"USER","ADMIN"})
    public List<Product> findAll() {
        return this.productRepository.findAll().list();
    }

    @Mutation
    @Description("Create a new Product")
    @RolesAllowed("ADMIN")
    public Boolean createProduct(String name, Double price) {
        return this.productRepository.createProduct(name, price);
    }
}
</code>```

I want to be able to send a GraphQL query (with Authentication inactivated/or not) in unit testing in order to validate my annotations but I don't find any documented way to do it.

答:
There is a great example documented at https://claudioaltamura.de/api/graphql-apis-with-quarkus with source code at https://github.com/claudioaltamura/quarkus-graphql-superheroes. Based on that when using the official demo code at https://quarkus.io/guides/smallrye-graphql we can write this test:

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.text.StringEscapeUtils;
import org.junit.jupiter.api.Test;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;

class GqlTestHelpers {

    @SneakyThrows
    public static String loadQueryAsJson(String resource) {
        Path path = Paths.get(resource);
        String allLines = Files.readAllLines(path).stream().collect(Collectors.joining("\n"));
        val quotedQuery = StringEscapeUtils.escapeJson(allLines);
        val json = "{ \"query\": \"" + quotedQuery + "\"}";
        return json;
    }
}

@QuarkusTest
@Slf4j
public class FilmResourceTest {

    @Test
    public void testQuery() {

        val query = GqlTestHelpers.loadQueryAsJson("src/test/resources/allFilms.gql");

        final Response response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(query)
                .when()
                .post("/graphql")
                .then()
                .assertThat()
                .statusCode(200)
                .and()
                .extract()
                .response();

        log.info(response.body().prettyPrint());

        final List<Film> films = response.jsonPath().getList("data.allFilms", Film.class);
        log.info(films.toString());

        assertThat(films)
                .isNotEmpty()
                .hasSize(3)
                .extracting(Film::getTitle)
                .contains("A New Hope", "The Empire Strikes Back", "Return Of The Jedi");
    }
}
```
<p>The very powerful assert statement at the end uses the amazing <code>assertj</code> library:</p>
<pre class="lang-xml prettyprint-override"><code>    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.20.2</version>
      <scope>test</scope>
    </dependency>
</code>```

Body:
In a quarkus project with quarkus-smallrye-graphql lib, is there a way to unit test a GraphQL resource object like this one :

@GraphQLApi
public class ProductResource {

    @Inject
    private ProductRepository productRepository;

    @Query("products")
    @Description("Get all Products")
    @RolesAllowed({"USER","ADMIN"})
    public List<Product> findAll() {
        return this.productRepository.findAll().list();
    }

    @Mutation
    @Description("Create a new Product")
    @RolesAllowed("ADMIN")
    public Boolean createProduct(String name, Double price) {
        return this.productRepository.createProduct(name, price);
    }
}

I want to be able to send a GraphQL query (with Authentication inactivated/or not) in unit testing in order to validate my annotations but I don't find any documented way to do it.

Body:
There is a great example documented at https://claudioaltamura.de/api/graphql-apis-with-quarkus with source code at https://github.com/claudioaltamura/quarkus-graphql-superheroes. Based on that when using the official demo code at https://quarkus.io/guides/smallrye-graphql we can write this test:

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.text.StringEscapeUtils;
import org.junit.jupiter.api.Test;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;

class GqlTestHelpers {

    @SneakyThrows
    public static String loadQueryAsJson(String resource) {
        Path path = Paths.get(resource);
        String allLines = Files.readAllLines(path).stream().collect(Collectors.joining("\n"));
        val quotedQuery = StringEscapeUtils.escapeJson(allLines);
        val json = "{ \"query\": \"" + quotedQuery + "\"}";
        return json;
    }
}

@QuarkusTest
@Slf4j
public class FilmResourceTest {

    @Test
    public void testQuery() {

        val query = GqlTestHelpers.loadQueryAsJson("src/test/resources/allFilms.gql");

        final Response response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(query)
                .when()
                .post("/graphql")
                .then()
                .assertThat()
                .statusCode(200)
                .and()
                .extract()
                .response();

        log.info(response.body().prettyPrint());

        final List<Film> films = response.jsonPath().getList("data.allFilms", Film.class);
        log.info(films.toString());

        assertThat(films)
                .isNotEmpty()
                .hasSize(3)
                .extracting(Film::getTitle)
                .contains("A New Hope", "The Empire Strikes Back", "Return Of The Jedi");
    }
}

The very powerful assert statement at the end uses the amazing assertj library:

    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>3.20.2</version>
      <scope>test</scope>
    </dependency>


问:
Firebase Authentication Emulator UI in docker container doesn't work on localhost
I have this dockerfile:

FROM node:16

ADD . /src
WORKDIR /src
# Install OpenJDK-11
RUN echo 'deb http://ftp.debian.org/debian stretch-backports main' | tee /etc/apt/sources.list.d/stretch-backports.list

RUN apt-get update && \
    apt-get install -y openjdk-11-jre-headless && \
    apt-get clean;
RUN npm i -g firebase-tools
RUN firebase --version
EXPOSE 9099 4000
```
<p>I have this firebase.json:</p>
<pre class="lang-json prettyprint-override"><code>{
  "emulators": {
    "auth": {
      "port": 9099
    },
    "ui": {
      "enabled": true,
      "port": 4000
    }
  }
}
</code>```

I have this docker-compose file:

version: "3.0"
services:
  firebase:
    build:
      context: .
      dockerfile: Dockerfile.firebase-emulator
    volumes:
      - ./fb-data:/src
    ports:
      - "9099:9099"
      - "4000:4000"
    stdin_open: true
    tty: true
```

Then I run docker exec -it <container-id> sh and start running these commands inside:

firebase login --no-localhost

firebase emulators:start --project demo-test

The result is this:

When I access in the browser the http://localhost:4000/auth
the result is:

Is there something wrong with the exposed docker ports?

Thx for any help!

答:
After more digging, to make this work, the firebase.json needs to have the "host" attribute:

{
  "emulators": {
    "auth": {
      "port": 9099,
      "host": "0.0.0.0"
    },
    "ui": {
      "enabled": true,
      "host": "0.0.0.0",
      "port": 4000
    }
  }
}

```

Body:
I have this dockerfile:

FROM node:16

ADD . /src
WORKDIR /src
# Install OpenJDK-11
RUN echo 'deb http://ftp.debian.org/debian stretch-backports main' | tee /etc/apt/sources.list.d/stretch-backports.list

RUN apt-get update && \
    apt-get install -y openjdk-11-jre-headless && \
    apt-get clean;
RUN npm i -g firebase-tools
RUN firebase --version
EXPOSE 9099 4000

I have this firebase.json:

{
  "emulators": {
    "auth": {
      "port": 9099
    },
    "ui": {
      "enabled": true,
      "port": 4000
    }
  }
}

I have this docker-compose file:

version: "3.0"
services:
  firebase:
    build:
      context: .
      dockerfile: Dockerfile.firebase-emulator
    volumes:
      - ./fb-data:/src
    ports:
      - "9099:9099"
      - "4000:4000"
    stdin_open: true
    tty: true

Then I run docker exec -it <container-id> sh and start running these commands inside:

firebase login --no-localhost

firebase emulators:start --project demo-test

The result is this:

When I access in the browser the http://localhost:4000/auth
the result is:

Is there something wrong with the exposed docker ports?

Thx for any help!


问:
Celery Schedule, can't pickle nowfun
I'm trying to configure Celery to run different tasks in different time zones maintaining the shift in daylight savings.  I set up my task like this:

```<code>import datetime
import pytz
from celery import Celery
from celery.schedules import crontab

app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

NOW_MT = lambda: datetime.datetime.now(pytz.timezone('America/Denver'))

app.conf.beat_schedule = {
    "My Daily Mountain Time Task": {
        "task": "app.tasks.some_task",
        "schedule": crontab(minute='0', hour='0', nowfun=NOW_MT)
    },
    "My Daily UTC Task": {
        "task": "app.tasks.some_other_task",
        "schedule": crontab(minute='0', hour='0')
    }
}
</code>```

But my celery beat process is erring out with the following message:

```<code>Can't pickle <function <lambda> at 0x7f71055a4670>: attribute lookup <lambda> on app.celery failed
</code>```

答:
Use the function instead of lambda functions</p>
```<code>import datetime
import pytz
from celery import Celery
from celery.schedules import crontab

app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

def NOW_MT():
    return datetime.datetime.now(pytz.timezone('America/Denver'))

app.conf.beat_schedule = {
    "My Daily Mountain Time Task": {
        "task": "app.tasks.some_task",
        "schedule": crontab(minute='0', hour='0', nowfun=NOW_MT)
    },
    "My Daily UTC Task": {
        "task": "app.tasks.some_other_task",
        "schedule": crontab(minute='0', hour='0')
    }
}
</code>```

Title: Celery Schedule, can't pickle nowfun

Body:
I'm trying to configure Celery to run different tasks in different time zones maintaining the shift in daylight savings.  I set up my task like this:

import datetime
import pytz
from celery import Celery
from celery.schedules import crontab

app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

NOW_MT = lambda: datetime.datetime.now(pytz.timezone('America/Denver'))

app.conf.beat_schedule = {
    "My Daily Mountain Time Task": {
        "task": "app.tasks.some_task",
        "schedule": crontab(minute='0', hour='0', nowfun=NOW_MT)
    },
    "My Daily UTC Task": {
        "task": "app.tasks.some_other_task",
        "schedule": crontab(minute='0', hour='0')
    }
}

But my celery beat process is erring out with the following message:

Can't pickle <function <lambda> at 0x7f71055a4670>: attribute lookup <lambda> on app.celery failed

Body:
Use the function instead of lambda functions

import datetime
import pytz
from celery import Celery
from celery.schedules import crontab

app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

def NOW_MT():
    return datetime.datetime.now(pytz.timezone('America/Denver'))

app.conf.beat_schedule = {
    "My Daily Mountain Time Task": {
        "task": "app.tasks.some_task",
        "schedule": crontab(minute='0', hour='0', nowfun=NOW_MT)
    },
    "My Daily UTC Task": {
        "task": "app.tasks.some_other_task",
        "schedule": crontab(minute='0', hour='0')
    }
}


问:
Python Webscraping looping pages
I recently started my very first Data Science project. I want to analyze specific job offers and therefore need to gather some data from a job portal.

Unfortunately I am already stuck at the very beginning. I seem to have some troubles with looping trough pages. I know there are already similar questions but none of the answers seems to help me (or maybe I simply do not understand them)

When scraping a single page I get exactly the result I am looking for

e.g.

```<code>       Firma: Greiner AG , Job:  Controller (m/w/d)  , Arbeitsort: Sattledt , Online seit 8.2.2022
</code>```

but as soon as I try to loop through pages I get an error message

Traceback (most recent call last):
File "e:\Programmieren\Projects\Webscraping\laola1_scraper.py", line 18, in
job_title = jobs.find('h2', class_ = 'm-jobsListItem__title').text
AttributeError: 'NoneType' object has no attribute 'text'

I also already tested to start with page 2 --> in that case I get a result  5 lines as intended and after that there is the error message again

I checked the position of the website where my code breaks but there is for sure no change in structure like mentioned in other cases

sitting here for almost 3 hours now but can't find any solution - guess it's pretty simple but what do i miss?

```<code>import requests
from bs4 import BeautifulSoup as bs

    url_job = "https://www.karriere.at/jobs/controller-controlling/ober%C3%B6sterreich-zentralraum"

    #response = requests.get(url_job)

    for page in range(2,10):

        response = requests.get(url_job + "?page=" + str(page))
        data = bs(response.content, 'lxml')

        job = data.find_all('li', class_ = 'm-jobsList__item')

        for jobs in job:
                job_title = jobs.find('h2', class_ = 'm-jobsListItem__title').text
                job_company = jobs.find('div', class_ ='m-jobsListItem__company').text
                job_location = jobs.find('li', class_ ='m-jobsListItem__location').text
                job_date = jobs.find('span', class_ ='m-jobsListItem__date').text.replace("am","")

                print(f'''
                Firma:{job_company}, Job:{job_title}, Arbeitsort:{job_location}, Online seit{job_date}
                ''')
</code>```

Thanks in advance

best, bones

答:
Your code is almost ok, but you want to skip specific items (e.g. ads) which don't contain job offer:

import requests
from bs4 import BeautifulSoup as bs

url_job = "https://www.karriere.at/jobs/controller-controlling/ober%C3%B6sterreich-zentralraum"

for page in range(10):
    response = requests.get(url_job + "?page=" + str(page))
    data = bs(response.content, "lxml")

    job = data.find_all("li", class_="m-jobsList__item")

    for jobs in job:
        # skip specific classes:
        if jobs.select_one(".m-brandingSolutionAdCard, .m-alarmDisruptor"):
            continue

        job_title = jobs.find("h2", class_="m-jobsListItem__title").text
        job_company = jobs.find("div", class_="m-jobsListItem__company").text
        job_location = jobs.find("li", class_="m-jobsListItem__location").text
        job_date = jobs.find(
            "span", class_="m-jobsListItem__date"
        ).text.replace("am", "")

        print(
            f"""Firma:{job_company}, Job:{job_title}, Arbeitsort:{job_location}, Online seit{job_date}"""
        )
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>Firma: Oberbank AG , Job:  MitarbeiterIn Kostenmanagement (m/w/d)  , Arbeitsort: Linz , Online seit 5.2.2022
Firma: TOURISMUSVERBAND Region WELS , Job:  MitarbeiterIn Buchhaltung und Kostenrechnung (Teilzeit bis 20 h)  , Arbeitsort: Wels , Online seit 8.2.2022
Firma: Oberbank AG , Job:  Junior Controller (m/w/d) - Karrierechance für BerufseinsteigerInnen  , Arbeitsort: Linz , Online seit 8.2.2022
Firma: WIFI Oberösterreich , Job:  Controlling/Kostenrechnung  , Arbeitsort: Linz , Online seit 7.2.2022
Firma: Schlüsselbauer Technology GmbH & Co KG , Job:  Kostenrechner - Controller (m/w/d)  , Arbeitsort: Gaspoltshofen , Online seit 1.2.2022
Firma: ISG Personalmanagement GmbH , Job:  Controller - Schwerpunkt HR (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: ISG Personalmanagement GmbH , Job:  Financial Controller (m/w/d)  , Arbeitsort: Linz , Online seit 5.2.2022
Firma: Schulmeister Finance , Job:  (Junior) Controller mit ausgezeichneten Entwicklungsmöglichkeiten (m/w/d)  , Arbeitsort: Wels , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Controller (m/w/d) für Non Profit Organisation  , Arbeitsort: Linz , Online seit 2.2.2022
Firma: VACE Engineering GmbH , Job:  Financial Controller (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Schulmeister Finance , Job:  (Senior) Controller (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: ÖSWAG Maschinenbau GmbH , Job:  Controller / Bilanzbuchhalter (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Maschinenring Personal und Service eGen , Job:  (Senior-)Controller/in (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Schulmeister Finance , Job:  Junior-Controller (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Senior Controller (m/w/d) für innovatives Geschäftsfeld  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Serviceorientierter Controller mit Hands-On-Mentalität (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: TGW Logistics Group , Job:  Group Controller (m/w/d)  , Arbeitsort: Marchtrenk , Online seit 9.2.2022

...and so on.
</code>```

Title: Python Webscraping looping pages

Body:
I recently started my very first Data Science project. I want to analyze specific job offers and therefore need to gather some data from a job portal.

Unfortunately I am already stuck at the very beginning. I seem to have some troubles with looping trough pages. I know there are already similar questions but none of the answers seems to help me (or maybe I simply do not understand them)

When scraping a single page I get exactly the result I am looking for

e.g.

       Firma: Greiner AG , Job:  Controller (m/w/d)  , Arbeitsort: Sattledt , Online seit 8.2.2022

but as soon as I try to loop through pages I get an error message

Traceback (most recent call last):
File "e:\Programmieren\Projects\Webscraping\laola1_scraper.py", line 18, in
job_title = jobs.find('h2', class_ = 'm-jobsListItem__title').text
AttributeError: 'NoneType' object has no attribute 'text'

I also already tested to start with page 2 --> in that case I get a result  5 lines as intended and after that there is the error message again

I checked the position of the website where my code breaks but there is for sure no change in structure like mentioned in other cases

sitting here for almost 3 hours now but can't find any solution - guess it's pretty simple but what do i miss?

import requests
from bs4 import BeautifulSoup as bs

    url_job = "https://www.karriere.at/jobs/controller-controlling/ober%C3%B6sterreich-zentralraum"

    #response = requests.get(url_job)

    for page in range(2,10):

        response = requests.get(url_job + "?page=" + str(page))
        data = bs(response.content, 'lxml')

        job = data.find_all('li', class_ = 'm-jobsList__item')

        for jobs in job:
                job_title = jobs.find('h2', class_ = 'm-jobsListItem__title').text
                job_company = jobs.find('div', class_ ='m-jobsListItem__company').text
                job_location = jobs.find('li', class_ ='m-jobsListItem__location').text
                job_date = jobs.find('span', class_ ='m-jobsListItem__date').text.replace("am","")

                print(f'''
                Firma:{job_company}, Job:{job_title}, Arbeitsort:{job_location}, Online seit{job_date}
                ''')

Thanks in advance

best, bones

Body:
Your code is almost ok, but you want to skip specific items (e.g. ads) which don't contain job offer:

import requests
from bs4 import BeautifulSoup as bs

url_job = "https://www.karriere.at/jobs/controller-controlling/ober%C3%B6sterreich-zentralraum"

for page in range(10):
    response = requests.get(url_job + "?page=" + str(page))
    data = bs(response.content, "lxml")

    job = data.find_all("li", class_="m-jobsList__item")

    for jobs in job:
        # skip specific classes:
        if jobs.select_one(".m-brandingSolutionAdCard, .m-alarmDisruptor"):
            continue

        job_title = jobs.find("h2", class_="m-jobsListItem__title").text
        job_company = jobs.find("div", class_="m-jobsListItem__company").text
        job_location = jobs.find("li", class_="m-jobsListItem__location").text
        job_date = jobs.find(
            "span", class_="m-jobsListItem__date"
        ).text.replace("am", "")

        print(
            f"""Firma:{job_company}, Job:{job_title}, Arbeitsort:{job_location}, Online seit{job_date}"""
        )

Prints:

Firma: Oberbank AG , Job:  MitarbeiterIn Kostenmanagement (m/w/d)  , Arbeitsort: Linz , Online seit 5.2.2022
Firma: TOURISMUSVERBAND Region WELS , Job:  MitarbeiterIn Buchhaltung und Kostenrechnung (Teilzeit bis 20 h)  , Arbeitsort: Wels , Online seit 8.2.2022
Firma: Oberbank AG , Job:  Junior Controller (m/w/d) - Karrierechance für BerufseinsteigerInnen  , Arbeitsort: Linz , Online seit 8.2.2022
Firma: WIFI Oberösterreich , Job:  Controlling/Kostenrechnung  , Arbeitsort: Linz , Online seit 7.2.2022
Firma: Schlüsselbauer Technology GmbH & Co KG , Job:  Kostenrechner - Controller (m/w/d)  , Arbeitsort: Gaspoltshofen , Online seit 1.2.2022
Firma: ISG Personalmanagement GmbH , Job:  Controller - Schwerpunkt HR (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: ISG Personalmanagement GmbH , Job:  Financial Controller (m/w/d)  , Arbeitsort: Linz , Online seit 5.2.2022
Firma: Schulmeister Finance , Job:  (Junior) Controller mit ausgezeichneten Entwicklungsmöglichkeiten (m/w/d)  , Arbeitsort: Wels , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Controller (m/w/d) für Non Profit Organisation  , Arbeitsort: Linz , Online seit 2.2.2022
Firma: VACE Engineering GmbH , Job:  Financial Controller (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Schulmeister Finance , Job:  (Senior) Controller (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: ÖSWAG Maschinenbau GmbH , Job:  Controller / Bilanzbuchhalter (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Maschinenring Personal und Service eGen , Job:  (Senior-)Controller/in (m/w/d)  , Arbeitsort: Linz , Online seit 10.2.2022
Firma: Schulmeister Finance , Job:  Junior-Controller (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Senior Controller (m/w/d) für innovatives Geschäftsfeld  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: Schulmeister Finance , Job:  Serviceorientierter Controller mit Hands-On-Mentalität (m/w/d)  , Arbeitsort: Linz , Online seit 9.2.2022
Firma: TGW Logistics Group , Job:  Group Controller (m/w/d)  , Arbeitsort: Marchtrenk , Online seit 9.2.2022

...and so on.


问:
Finding maximum

Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

```<code>5
1 3 2 5 4
</code>```

Output

```<code>21
</code>```

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

```<code>n<=10^6
a[i]>0 with 1<=i<=n
</code>```

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?

答:
First, let's reference the "brute force" force algorithm.  This will have some issues, that I will call out below, but it is a correct solution.

```<code>struct Result
{
    size_t i;
    size_t j;
    int64_t value;
};

Result findBestBruteForce(const vector<int>& a)
{
    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        for (size_t j = i + 1; j < a.size(); j++)
        {
            // do the math in 64-bit space to avoid overflow
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
    }
    return { besti, bestj, bestvalue };
}
</code>```

The problem with the above code is that it runs at O(N²).  Or more precisely, for the the N iterations of the outer for-loop (where i goes from 0 to N), there are an average of N/2 iterations on the inner for-loop.  If N is small, this isn't a problem.

On my PC, with full optimizations turned on. When is N under 20000, the run time is less than a second.  Once N approaches 100000, it takes several seconds to process the 5 billion iterations. Let's just go with a "billion operations per second" as an expected rate.  If N were to 1000000, the maximum as the OP outlined, it would probably take 500 seconds.  Such is the nature of a N-squared algorithm.

So how can we speed it up?  Here's an interesting observation.  Let's say our array was this:

10 5 4 15 13 100 101 6

On the first iteration of the outer loop above, where i=0, we'd be computing this on each iteration of the inner loop:

```<code>for each j: (a[0]+a[j])(j-0)
for each j: (10+a[j])(j-0)
for each j: [15*1, 14*2, 25*3, 23*4, 1000*5, 1010*6, 16*6]
         =  [15,     28,   75,   92,   5000,   6060,   96]
</code>```

Hence, for when i=0, a[i] = 15 and the largest value computed from that set is 6060.

Since A[0] is 15, and we're tracking a current "best" value, there's no incentive to iterate all the values again for i=1 since a[1]==14 is less than 15.  There's no j index that would compute a value of (a[1]+a[j])*(j-1) larger than what's already been found.  Because (14+a[j])*(j-1) will always be less than (15+a[j])*(j-1).  (Assumes all values in the array are non-negative).

So to generalize, the outer loop can skip over any index of i where A[best_i] > A[i].  And that's a real simple alteration to our above code:

```<code>Result findBestOptimized(const std::vector<int>& a)
{

    if (a.size() < 2)
    {
        return {0,0,INT64_MIN};
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        if (a[i] <= minimum)
        {
            continue;
        }

        for (size_t j = i + 1; j < a.size(); j++)
        {
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
                minimum = a[i];
            }
        }
    }

    return { besti, bestj, bestvalue };
}
</code>```

Above, we introduce a minimum value for A[i] to be before considering doing the full inner loop enumeration.

I benchmarked this with build optimizations on. On a random array of a million items, it runs in under a second.

But wait... there's another optimization!

If the inner loop fails to find an index j such that value > bestvalue, then we already know that the current A[i] is greater than minimum. Hence, we can increment minimum to A[i] regardless at the end of the inner loop.

Now, I'll present the final solution:

```<code>Result findBestOptimizedEvenMore(const std::vector<int>& a)
{

    if (a.size() < 2)
    {
        return { 0,0,INT64_MIN };
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        if (a[i] <= minimum)
        {
            continue;
        }

        for (size_t j = i + 1; j < a.size(); j++)
        {
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
        minimum = a[i]; // since we know a[i] > minimum, we can do this

    }

    return { besti, bestj, bestvalue };
}
</code>```

I benchmarked the above solution on different array sizes from N=100 to N=1000000.  It does all iterations in under 25 milliseconds.

In the above solution, there's likely a worst case runtime of O(N²) again when all the items in the array are in ascending order. But I believe the average case should be on the order of O(N lg N) or better.  I'll do some more analysis later if anyone is interested.

Title: Finding maximum

Body:
Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

5
1 3 2 5 4

Output

21

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

n<=10^6
a[i]>0 with 1<=i<=n

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?

Body:
First, let's reference the "brute force" force algorithm.  This will have some issues, that I will call out below, but it is a correct solution.

struct Result
{
    size_t i;
    size_t j;
    int64_t value;
};

Result findBestBruteForce(const vector<int>& a)
{
    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        for (size_t j = i + 1; j < a.size(); j++)
        {
            // do the math in 64-bit space to avoid overflow
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
    }
    return { besti, bestj, bestvalue };
}

The problem with the above code is that it runs at O(N²).  Or more precisely, for the the N iterations of the outer for-loop (where i goes from 0 to N), there are an average of N/2 iterations on the inner for-loop.  If N is small, this isn't a problem.

On my PC, with full optimizations turned on. When is N under 20000, the run time is less than a second.  Once N approaches 100000, it takes several seconds to process the 5 billion iterations. Let's just go with a "billion operations per second" as an expected rate.  If N were to 1000000, the maximum as the OP outlined, it would probably take 500 seconds.  Such is the nature of a N-squared algorithm.

So how can we speed it up?  Here's an interesting observation.  Let's say our array was this:

10 5 4 15 13 100 101 6

On the first iteration of the outer loop above, where i=0, we'd be computing this on each iteration of the inner loop:

for each j: (a[0]+a[j])(j-0)
for each j: (10+a[j])(j-0)
for each j: [15*1, 14*2, 25*3, 23*4, 1000*5, 1010*6, 16*6]
         =  [15,     28,   75,   92,   5000,   6060,   96]

Hence, for when i=0, a[i] = 15 and the largest value computed from that set is 6060.

Since A[0] is 15, and we're tracking a current "best" value, there's no incentive to iterate all the values again for i=1 since a[1]==14 is less than 15.  There's no j index that would compute a value of (a[1]+a[j])*(j-1) larger than what's already been found.  Because (14+a[j])*(j-1) will always be less than (15+a[j])*(j-1).  (Assumes all values in the array are non-negative).

So to generalize, the outer loop can skip over any index of i where A[best_i] > A[i].  And that's a real simple alteration to our above code:

Result findBestOptimized(const std::vector<int>& a)
{

    if (a.size() < 2)
    {
        return {0,0,INT64_MIN};
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        if (a[i] <= minimum)
        {
            continue;
        }

        for (size_t j = i + 1; j < a.size(); j++)
        {
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
                minimum = a[i];
            }
        }
    }

    return { besti, bestj, bestvalue };
}

Above, we introduce a minimum value for A[i] to be before considering doing the full inner loop enumeration.

I benchmarked this with build optimizations on. On a random array of a million items, it runs in under a second.

But wait... there's another optimization!

If the inner loop fails to find an index j such that value > bestvalue, then we already know that the current A[i] is greater than minimum. Hence, we can increment minimum to A[i] regardless at the end of the inner loop.

Now, I'll present the final solution:

Result findBestOptimizedEvenMore(const std::vector<int>& a)
{

    if (a.size() < 2)
    {
        return { 0,0,INT64_MIN };
    }

    size_t besti = 0;
    size_t bestj = 0;
    int64_t bestvalue = INT64_MIN;
    int minimum = INT_MIN;

    for (size_t i = 0; i < a.size(); i++)
    {
        if (a[i] <= minimum)
        {
            continue;
        }

        for (size_t j = i + 1; j < a.size(); j++)
        {
            int64_t value = (a[i] + (int64_t)a[j]) * (j - i);
            if (value > bestvalue)
            {
                bestvalue = value;
                besti = i;
                bestj = j;
            }
        }
        minimum = a[i]; // since we know a[i] > minimum, we can do this

    }

    return { besti, bestj, bestvalue };
}

I benchmarked the above solution on different array sizes from N=100 to N=1000000.  It does all iterations in under 25 milliseconds.

In the above solution, there's likely a worst case runtime of O(N²) again when all the items in the array are in ascending order. But I believe the average case should be on the order of O(N lg N) or better.  I'll do some more analysis later if anyone is interested.


问:
Entity Framework Db context issue in .net core related to Models
Am Trying to create Two Tables like bellow got some EF error.

```<code>public class Student : ModelsBase
    {
        public string AdharNumber { get; set; }
        public byte Religion { get; set; }
        public int CategoryID { get; set; }
        public string Cast { get; set; }
        public string SubCast { get; set; }
        public string Photo { get; set; }
        public DateTime DateOfJoining { get; set; } = DateTime.Now;

        [Required]
        public ICollection<Address> TemporaryAddress { get; set; }

        [Required]
        public ICollection<Address> PermanentAddress { get; set; }
}

 public class Address : ModelsBase
    {
        public string DoorNo { get; set; }
        public string StreetLocality { get; set; }
        public string Landmark { get; set; }
        public string City { get; set; }
        public int Taluk { get; set; }
        public int District { get; set; }
        public int State { get; set; }
        public string Pincode { get; set; }
        public bool IsPermanent { get; set; } = true;
        public bool IsDefault { get; set; } = true;

        [ForeignKey("Student")]
        public Guid StudentId { get; set; }
    }
</code>```

Getting the bellow error while trying to Run the "Add-Migration command"

Both relationships between 'Address' and 'Student.PermanentAddress' and between 'Address' and 'Student.TemporaryAddress' could use {'StudentId'} as the foreign key. To resolve this, configure the foreign key properties explicitly in 'OnModelCreating' on at least one of the relationships

Please help. Thanks!

答:
Your issue is that from the Address side of things you have a Many-to-1 with a single Student, but from the Student side of things you want 2x 1-to-Many relationships.

Since The relationship is really just a 1-to-Many from the student that you want to discriminate between temporary and permanent addresses:

```<code>public class Student : ModelsBase
{
    public string AdharNumber { get; set; }
    public byte Religion { get; set; }
    public int CategoryID { get; set; }
    public string Cast { get; set; }
    public string SubCast { get; set; }
    public string Photo { get; set; }
    public DateTime DateOfJoining { get; set; } = DateTime.Now;

    [Required]
    public ICollection<Address> Addresses { get; set; } = new List<Address>();

    [NotMapped]
    public ICollection<Address> TemporaryAddresses => Addresses.Where(x => !x.IsPermanent).ToList();

    [NotMapped]
    public ICollection<Address> PermanentAddresses => Addresses.Where(x => x.IsPermanent).ToList();

}
</code>```

With 1-to-many collections I recommend initializing them to an empty list to avoid null reference exceptions especially if lazy loading is disabled.

The caveat here is that from EF's perspective, Student only has the Addresses collection, do not attempt to use either TemporaryAddresses or PermanentAddresses in a query expression as these are unmapped accessors. If you want to filter based on a permanent address you will have to do it through Addresses and include the condition on IsPermanent in the query.

For example:

```<code>// Not valid...
var studentsInDetroit = context.Students.Where(x => x.PermanentAddresses.Any(a => a.City == "Detroit")).ToList();

// Valid...
var studentsInDetroit = context.Students.Where(x => x.Addresses.Any(a => a.IsPermanent && a.City == "Detroit")).ToList();
</code>```

Normally I don't recommend using unmapped accessors in entities because of this. It is generally better to leave entities representing pure domain/data state and project that down to view models which can be more concerned about splitting the data into a more palatable form for consumption.

Body:
Am Trying to create Two Tables like bellow got some EF error.

public class Student : ModelsBase
    {
        public string AdharNumber { get; set; }
        public byte Religion { get; set; }
        public int CategoryID { get; set; }
        public string Cast { get; set; }
        public string SubCast { get; set; }
        public string Photo { get; set; }
        public DateTime DateOfJoining { get; set; } = DateTime.Now;

        [Required]
        public ICollection<Address> TemporaryAddress { get; set; }

        [Required]
        public ICollection<Address> PermanentAddress { get; set; }
}

 public class Address : ModelsBase
    {
        public string DoorNo { get; set; }
        public string StreetLocality { get; set; }
        public string Landmark { get; set; }
        public string City { get; set; }
        public int Taluk { get; set; }
        public int District { get; set; }
        public int State { get; set; }
        public string Pincode { get; set; }
        public bool IsPermanent { get; set; } = true;
        public bool IsDefault { get; set; } = true;

        [ForeignKey("Student")]
        public Guid StudentId { get; set; }
    }

Getting the bellow error while trying to Run the "Add-Migration command"

Both relationships between 'Address' and 'Student.PermanentAddress' and between 'Address' and 'Student.TemporaryAddress' could use {'StudentId'} as the foreign key. To resolve this, configure the foreign key properties explicitly in 'OnModelCreating' on at least one of the relationships

Please help. Thanks!

Body:
Your issue is that from the Address side of things you have a Many-to-1 with a single Student, but from the Student side of things you want 2x 1-to-Many relationships.

Since The relationship is really just a 1-to-Many from the student that you want to discriminate between temporary and permanent addresses:

public class Student : ModelsBase
{
    public string AdharNumber { get; set; }
    public byte Religion { get; set; }
    public int CategoryID { get; set; }
    public string Cast { get; set; }
    public string SubCast { get; set; }
    public string Photo { get; set; }
    public DateTime DateOfJoining { get; set; } = DateTime.Now;

    [Required]
    public ICollection<Address> Addresses { get; set; } = new List<Address>();

    [NotMapped]
    public ICollection<Address> TemporaryAddresses => Addresses.Where(x => !x.IsPermanent).ToList();

    [NotMapped]
    public ICollection<Address> PermanentAddresses => Addresses.Where(x => x.IsPermanent).ToList();

}

With 1-to-many collections I recommend initializing them to an empty list to avoid null reference exceptions especially if lazy loading is disabled.

The caveat here is that from EF's perspective, Student only has the Addresses collection, do not attempt to use either TemporaryAddresses or PermanentAddresses in a query expression as these are unmapped accessors. If you want to filter based on a permanent address you will have to do it through Addresses and include the condition on IsPermanent in the query.

For example:

// Not valid...
var studentsInDetroit = context.Students.Where(x => x.PermanentAddresses.Any(a => a.City == "Detroit")).ToList();

// Valid...
var studentsInDetroit = context.Students.Where(x => x.Addresses.Any(a => a.IsPermanent && a.City == "Detroit")).ToList();

Normally I don't recommend using unmapped accessors in entities because of this. It is generally better to leave entities representing pure domain/data state and project that down to view models which can be more concerned about splitting the data into a more palatable form for consumption.


问:
Managing and viewing branches in a GIST
I created a gist and cloned it locally where I am happily managing it.  I also created a development branch and committed/pushed it (mainly as an exercise to understand git).  I can see and manage all of this using posh~git locally, but I can't find any trace of the new branch in my gists at https://gist.github.com or in my git repo's.

Is this a basic (and understandable) limitation of the gist interface or is there a way to select branches on a gist?

My motivation is to share rendered the gists using references to the included assets.

答:
but I can't find any trace of the new branch in my gists at https://gist.github.com or in my git repo's.

Not only gists do not support branches, but the default branch has just (Feb. 2022) changed:

Gists Now Support Alternative Default Branch Names

As you may or may not know, gists are actually Git repositories.

New gists are now created with a default branch name of either main or the alternative default branch name you've defined in your user settings.

(See git config --global init.defaultbranch xxx, in Git 2.28+, Q3 2020)

This matches how other repositories are created on GitHub.

More information about default branches

How to change the default branch name for new repositories

Learn more about the branch renaming effort in the github/renaming repository

ContentLicense: CC BY-SA 3.0

Title: Managing and viewing branches in a GIST


问:
JArray silently ignoring members
I'm trying to deserialize a snippet of JSON that looks something like this:

```<code>{
    "timePoints": [ "2020", "2020-1-9", "2020-4-1" ]
}
</code>```

The idea here is that we will allow either a fully qualified date, or just a year which will be converted to a nominal date. So I created a custom JsonConverter to handle this field:

```<code>public class Foo
{
    [JsonConverter(typeof(TimePointConverter))]
    public IEnumerable<DateTime> TimePoints { get; set; }
}

public class TimePointConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        reader.DateParseHandling = DateParseHandling.None;

        var obj = JArray.ReadFrom(reader);
        var points = obj.Select(x =>
        {
            if (!DateTime.TryParse(x.ToString(), out var date))
            {
                if (int.TryParse(x.ToString(), out int year) && year > 0)
                {
                    date = new DateTime(year, 10, 1);   // qtr 4
                }
                else
                {
                    throw new FormatException($"Unable to parse date: {x.ToString()} is invalid.");
                }
            }
            return date;
        });
        return points.Any() ? points.ToArray() : null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

But the problem is that JArray.ReadFrom will automatically try to interpret 2020-1-9 and 2020-4-1 as dates. But since 2020 isn't a date, it just ignores it altogether. So I end up with obj being an array of two dates silently ignore the third item. How do I stop this behavior? I want it to read these as strings, not as dates? DateParseHandling.None seems to have no effect at all.

Update: Turned out I was looking in the wrong place. This was being serialized somewhere else before it even got to the application I was looking at and that was removing the non-date item. Closing this question now...

答:
This works for me

Foo.cs

```<code>public sealed record Foo(IReadOnlyCollection<DateTime> TimePoints);
</code>```

Main method

```<code>    var json = @"
{
    ""timePoints"": [ ""2020"", ""2020-1-9"", ""2020-4-1"" ]
}";

    var settings = new JsonSerializerSettings
    {
        Converters = new List<JsonConverter> { new TimePointConverter() }
    };

    var foo = JsonConvert.DeserializeObject<Foo>(json, settings);
</code>```

Converter

```<code>public class TimePointConverter : JsonConverter
{
    public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        reader.DateParseHandling = DateParseHandling.None;

        var obj = JArray.ReadFrom(reader);
        // select 'timePoints' element from the json
        var points = obj["timePoints"]?.Select(x =>
        {
            if (!DateTime.TryParse(x.ToString(), out var date))
            {
                if (int.TryParse(x.ToString(), out int year) && year > 0)
                {
                    date = new DateTime(year, 10, 1);   // qtr 4
                }
                else
                {
                    throw new FormatException($"Unable to parse date: {x.ToString()} is invalid.");
                }
            }
            return date;
        });

        // returns a Foo rather than list of DateTimes
        return points is not null && points.Any()
            ? new Foo(points.ToArray())
            : null;
    }

    public override bool CanConvert(Type objectType)
        => true;

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        => throw new NotImplementedException();
}
</code>```

But I assumed you are calling DeserializeObject<Foo>

Title: JArray silently ignoring members

Body:
I'm trying to deserialize a snippet of JSON that looks something like this:

{
    "timePoints": [ "2020", "2020-1-9", "2020-4-1" ]
}

The idea here is that we will allow either a fully qualified date, or just a year which will be converted to a nominal date. So I created a custom JsonConverter to handle this field:

public class Foo
{
    [JsonConverter(typeof(TimePointConverter))]
    public IEnumerable<DateTime> TimePoints { get; set; }
}

public class TimePointConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        reader.DateParseHandling = DateParseHandling.None;

        var obj = JArray.ReadFrom(reader);
        var points = obj.Select(x =>
        {
            if (!DateTime.TryParse(x.ToString(), out var date))
            {
                if (int.TryParse(x.ToString(), out int year) && year > 0)
                {
                    date = new DateTime(year, 10, 1);   // qtr 4
                }
                else
                {
                    throw new FormatException($"Unable to parse date: {x.ToString()} is invalid.");
                }
            }
            return date;
        });
        return points.Any() ? points.ToArray() : null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

But the problem is that JArray.ReadFrom will automatically try to interpret 2020-1-9 and 2020-4-1 as dates. But since 2020 isn't a date, it just ignores it altogether. So I end up with obj being an array of two dates silently ignore the third item. How do I stop this behavior? I want it to read these as strings, not as dates? DateParseHandling.None seems to have no effect at all.

Update: Turned out I was looking in the wrong place. This was being serialized somewhere else before it even got to the application I was looking at and that was removing the non-date item. Closing this question now...

Body:
This works for me

Foo.cs

public sealed record Foo(IReadOnlyCollection<DateTime> TimePoints);

Main method

    var json = @"
{
    ""timePoints"": [ ""2020"", ""2020-1-9"", ""2020-4-1"" ]
}";

    var settings = new JsonSerializerSettings
    {
        Converters = new List<JsonConverter> { new TimePointConverter() }
    };

    var foo = JsonConvert.DeserializeObject<Foo>(json, settings);

Converter

public class TimePointConverter : JsonConverter
{
    public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        reader.DateParseHandling = DateParseHandling.None;

        var obj = JArray.ReadFrom(reader);
        // select 'timePoints' element from the json
        var points = obj["timePoints"]?.Select(x =>
        {
            if (!DateTime.TryParse(x.ToString(), out var date))
            {
                if (int.TryParse(x.ToString(), out int year) && year > 0)
                {
                    date = new DateTime(year, 10, 1);   // qtr 4
                }
                else
                {
                    throw new FormatException($"Unable to parse date: {x.ToString()} is invalid.");
                }
            }
            return date;
        });

        // returns a Foo rather than list of DateTimes
        return points is not null && points.Any()
            ? new Foo(points.ToArray())
            : null;
    }

    public override bool CanConvert(Type objectType)
        => true;

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        => throw new NotImplementedException();
}

But I assumed you are calling DeserializeObject<Foo>


问:
Append React Component to DOM
I want to append a React Element via Code to the friendList. How is this working?
Thanks for your help.

Image:

https://i.stack.imgur.com/1o3HJ.png

答:
In react, your shouldn't be appending anything to anything. This should be handled in state.

```<code>const [friends, setFriends] = useState([]);
</code>```

and then map over the friends in your render.

```<code>{ friends.map((friend) =>
  <div key={ friend.id }>
    <span>{ friend.id }</span>
    <span>{ friend.name }</span>
  </div>
)}
</code>```

Title: Append React Component to DOM

Body:
In react, your shouldn't be appending anything to anything. This should be handled in state.

const [friends, setFriends] = useState([]);

and then map over the friends in your render.

{ friends.map((friend) =>
  <div key={ friend.id }>
    <span>{ friend.id }</span>
    <span>{ friend.name }</span>
  </div>
)}


问:
How do I get the index of an appended object in jQuery
```<code>$("input").keypress(function(e){
    let value = $("input").val()
    if(e.which == 13 && value != ""){
        $("input").val("")
        $(".itemCategRow:nth-child(1)").append("<div class=\"button\">" + value + "</div>")
    }
})

$(".button").clicked(function(){
    alert($(this).index())
})
</code>```

nothing happens when I click the buttons, the reason for getting their certain indexes is to
remove certain buttons.

答:
Since the button is added dynamically, you can only listen to events on it through "event delegation". Try this

```<code>$(document).on("click", ".button", function(){
    alert($(this).index())
})
</code>```

Body:
$("input").keypress(function(e){
    let value = $("input").val()
    if(e.which == 13 && value != ""){
        $("input").val("")
        $(".itemCategRow:nth-child(1)").append("
" + value + "
")
    }
})

$(".button").clicked(function(){
    alert($(this).index())
})

nothing happens when I click the buttons, the reason for getting their certain indexes is to
remove certain buttons.

Body:
Since the button is added dynamically, you can only listen to events on it through "event delegation". Try this

$(document).on("click", ".button", function(){
    alert($(this).index())
})


问:
ListItem child doesn't fill full parent height (click counts as exit/escape)
I've implemented a drawer similar to the example shown here. For working reproductions, please follow the link above and edit the Responsive Drawer on Stackblitz or Codesandbox. All that needs to be done to see the issue is to add onClick={(e) => console.log(e.target.tagName)} to the <ListItem button>.

Everything works as expected, except if you click on the top/bottom edge of a ListItem - in that case, I'm not able to get to the value assigned to the ListItem, and it's treated like an escape/cancellation and closes the drawer. In the <ListItem> the method onClick={(e) => console.log(e.target.tagName) will correctly log SPAN if you click in the middle, but will log DIV and be unresponsive if you click on the edge.
Example of one of the list items:

```<code><Collapse in = {isOpen} timeout = 'auto' unmountOnExit>
    <List component = 'div' disablePadding>
        <ListItem button key = {'Something'} value = {'Something'} sx = {{pl: 4}} onClick = {(e) => handleSelect(e)}>
            <ListItemIcon><StarBorder /></ListItemIcon>
            <ListItemText primary = {'Something'} />
        </ListItem>
    </List>
</Collapse>
</code>```

Overall structure of the drawer:

```<code><List>
    <Box>
        <ListItem />
        <Collapse>
            <ListItem />
            <ListItem />
        </Collapse>
    </Box>
</List>
</code>```

onClick:

```<code>const handleSelect = (e) =>
{
    const parentTag = e.target.tagName

    if (parentTag === 'DIV')
    {
        console.log(e.target.innerHTML)

        for (let child of e.target.children)
        {
            if (child.tagName === 'SPAN')
            {
                console.log(child.innerHTML)
            }
        }

    }
    else if (parentTag === 'SPAN')
    {
        console.log(e.target.innerHTML)
    }
}
</code>```

If you were to click in the middle of a ListItem, then parentTag === 'SPAN', and the console will log Something as expected.

But if you click on the top or bottom edge, then parentTag === 'DIV', and console.log(e.target.innerHTML) will show the following:

```<code><div class="MuiListItemIcon-root..."><svg class="MuiSvgIcon-root..."><path d="..."></path>
</svg></div><div class="MuiListItemText-root..."><span class="MuiTypography-root...">
Something
</span></div><span class="MuiTouchRipple-root..."><span class="css..."><span
class="MuiTouchRipple..."></span></span></span>
</code>```

There are three  elements, and I need the value of the first. However, console.log(child.innerHTML) always logs the later ones:

```<code><span class="css..."><span
class="MuiTouchRipple..."></span></span>
</code>```

Is there a way to get to the actual value I need? Or a better way to handle this, maybe by making the
 unclickable/expanding the click area of the ListItem?

答:
That's actually a CSS problem. You need to make the child elements width and height equal to the parent elements width and height. This is true for every element which is inline by default and you want to work with it.

Here are some docs about the CSS box model:

box model

understanding the inline box model

In this case, you want to change the display element in ListItem to div

AKA

```<code><ListItem component="div">
    // some stuff
</ListItem>
</code>```

Body:
I've implemented a drawer similar to the example shown here. For working reproductions, please follow the link above and edit the Responsive Drawer on Stackblitz or Codesandbox. All that needs to be done to see the issue is to add onClick={(e) => console.log(e.target.tagName)} to the <ListItem button>.

Everything works as expected, except if you click on the top/bottom edge of a ListItem - in that case, I'm not able to get to the value assigned to the ListItem, and it's treated like an escape/cancellation and closes the drawer. In the <ListItem> the method onClick={(e) => console.log(e.target.tagName) will correctly log SPAN if you click in the middle, but will log DIV and be unresponsive if you click on the edge.
Example of one of the list items:

<Collapse in = {isOpen} timeout = 'auto' unmountOnExit>
    <List component = 'div' disablePadding>
        <ListItem button key = {'Something'} value = {'Something'} sx = {{pl: 4}} onClick = {(e) => handleSelect(e)}>
            <ListItemIcon><StarBorder /></ListItemIcon>
            <ListItemText primary = {'Something'} />
        </ListItem>
    </List>
</Collapse>

Overall structure of the drawer:

<List>
    <Box>
        <ListItem />
        <Collapse>
            <ListItem />
            <ListItem />
        </Collapse>
    </Box>
</List>

onClick:

const handleSelect = (e) =>
{
    const parentTag = e.target.tagName

    if (parentTag === 'DIV')
    {
        console.log(e.target.innerHTML)

        for (let child of e.target.children)
        {
            if (child.tagName === 'SPAN')
            {
                console.log(child.innerHTML)
            }
        }

    }
    else if (parentTag === 'SPAN')
    {
        console.log(e.target.innerHTML)
    }
}

If you were to click in the middle of a ListItem, then parentTag === 'SPAN', and the console will log Something as expected.

But if you click on the top or bottom edge, then parentTag === 'DIV', and console.log(e.target.innerHTML) will show the following:

<svg class="MuiSvgIcon-root..."><path d="..."></path>
</svg>

Something

There are three  elements, and I need the value of the first. However, console.log(child.innerHTML) always logs the later ones:

Is there a way to get to the actual value I need? Or a better way to handle this, maybe by making the
 unclickable/expanding the click area of the ListItem?

Body:
That's actually a CSS problem. You need to make the child elements width and height equal to the parent elements width and height. This is true for every element which is inline by default and you want to work with it.

Here are some docs about the CSS box model:

box model

understanding the inline box model

In this case, you want to change the display element in ListItem to div

AKA

<ListItem component="div">
    // some stuff
</ListItem>


问:
How to use chrono::microseconds with Pybind11?
The error boils down to this snippet.

#include <chrono>
#include <pybind11/chrono.h>
#include <pybind11/pybind11.h>

namespace chr = std::chrono;
namespace py = pybind11;

struct Time {
    chr::microseconds elapsed;

    Time(const chr::microseconds& elapsed) : elapsed(elapsed) {}
};

PYBIND11_MODULE(CppModule, m) {
    py::class_<Time>(m, "Time")
        .def(py::init<const chr::microseconds&>())
        .def("elapsed", &Time::elapsed);
}
```
<p>When I try to build it, I get the following error.</p>
<pre class="lang-none prettyprint-override"><code>'pybind11::cpp_function::cpp_function': no overloaded function takes 4 arguments
</code>```

What should I do to read Time::elapsed on the Python side?

答:
Method def binds functions. Methods def_readwrite and def_readonly bind fields.

Time::elapsed is a field. That's why def cannot be used.

PYBIND11_MODULE(CppModule, m) {
    py::class_<Time>(m, "Time")
        .def(py::init<const chr::microseconds&>())
        .def_readwrite("elapsed", &Time::elapsed);
}
```
<p>Note that on Python side type <code>chr::microseconds</code> is converted to <code>datetime.timedelta</code>. To get the total number of microseconds divide it by 1 microsecond.</p>
<pre class="lang-py prettyprint-override"><code>import CppModule as m
import datetime

t = m.Time(datetime.timedelta(minutes=10, seconds=5))
print(t.elapsed)
print(t.elapsed // datetime.timedelta(microseconds=1))
</code>```

Output.

0:10:05
605000000
```

Body:
The error boils down to this snippet.

#include <chrono>
#include <pybind11/chrono.h>
#include <pybind11/pybind11.h>

namespace chr = std::chrono;
namespace py = pybind11;

struct Time {
    chr::microseconds elapsed;

    Time(const chr::microseconds& elapsed) : elapsed(elapsed) {}
};

PYBIND11_MODULE(CppModule, m) {
    py::class_<Time>(m, "Time")
        .def(py::init<const chr::microseconds&>())
        .def("elapsed", &Time::elapsed);
}

When I try to build it, I get the following error.

'pybind11::cpp_function::cpp_function': no overloaded function takes 4 arguments

What should I do to read Time::elapsed on the Python side?

Body:
Method def binds functions. Methods def_readwrite and def_readonly bind fields.

Time::elapsed is a field. That's why def cannot be used.

PYBIND11_MODULE(CppModule, m) {
    py::class_<Time>(m, "Time")
        .def(py::init<const chr::microseconds&>())
        .def_readwrite("elapsed", &Time::elapsed);
}

Note that on Python side type chr::microseconds is converted to datetime.timedelta. To get the total number of microseconds divide it by 1 microsecond.

import CppModule as m
import datetime

t = m.Time(datetime.timedelta(minutes=10, seconds=5))
print(t.elapsed)
print(t.elapsed // datetime.timedelta(microseconds=1))

Output.

0:10:05
605000000


问:
Mongo DB High CPU Usage
Usually , what are the checks/actions we need to do when we receive an alert from MongoDB about CPU high usage like below?

**System: CPU (User) % has gone above 95

CPU usage is maxing out available resources and may be throttled shortly. Ensure no index is missing and scale up. Please navigate to the System CPU metrics page to see usage details.**

答:
Check if you have COLLSCAN queries in your mongo.log files -> this mean you dont use indexes and your performance is suffering unnecessary.

Check for other slow queries in your logs even using indexes.

CPU in mongoDB is used mainly for sorting and aggregation , check your queries.

It maybe your database growed enought and you need to think about resources extension or sharding?

Some commands that can be of help:

```<code> top -H -p <mongod PID>
 mongotop
 mongostat
 db.currentOp()
 sar
</code>```

Title: Mongo DB High CPU Usage

Body:
Check if you have COLLSCAN queries in your mongo.log files -> this mean you dont use indexes and your performance is suffering unnecessary.

Check for other slow queries in your logs even using indexes.

CPU in mongoDB is used mainly for sorting and aggregation , check your queries.

It maybe your database growed enought and you need to think about resources extension or sharding?

Some commands that can be of help:

 top -H -p <mongod PID>
 mongotop
 mongostat
 db.currentOp()
 sar


问:
ElasticSearch/OpenSearch historical histogram
I'm using ElasticSearch (OpenSearch) to store multiple objects in an index. Each object has a unique ID, creation date and an "amount" field that stores integer value. This "amount" value changes periodically, so I'm updating objects in-place using the IDs to match the existing objects.

What I want is to display a histogram of total amount across all objects over time. The problem is that I need to preserve historical data somehow in order for it to be displayed on the graph.

What are my option to implement this? Is there an automatic way to aggregate and preserve these totals? Or should I do this manually from my application? E.g. send these totals instead of individual objects?

The data structure:

[
  { id: '{uuidv4}', amount: 100 },
  { id: '{uuidv4}', amount: 25 },
  { id: '{uuidv4}', amount: 150 },
  { id: '{uuidv4}', amount: 0 },
  ...
]
```

答:
Elasticsearch isn't very fit for processing historical or time-series data. It has some good tooling for cases like logging but fails when the use case assume some continuity in the data, like metric gauges or real-world prices. It is technically possible to create a cron job that would retrieve current values every minute and store them somewhere but it will be inefficient and poorly scalable.

Instead, it would make sense to use a specialized time-series database, like InfluxDB that allow aggregations like that together with the ability to zoom in and out of the timeline.


问:
stderr out to a variable
I have a bash script that iterates through a list of file locations (filepath) and deletes them. I'd like to have any errors that the command throws (like permission issues) go to an individual log as it iterates through files. Like a confirmation that the delete actually happened.

So MASTERDELETELIST.txt has a list of DeleteMeList-Category-[A-Z].txt, each one then has lines like /foo/bar/deleteme-[01-99].txt (**brackets for illustration only)

As the script iterates, it creates a report specific to that CATEGORY list. I need to push it like so: exec 2> >> $ERRORSREPORT, which throws an error:

./script.sh: line 60: syntax error near unexpected token >>' ./script.sh: line 60:                  exec 2> >> $ERRORSREPORT'

*exact output from Terminal makes the formatting errors above)

..or exec 2> $ERRORREPORT which doesn't seem to output anything.. when a file cannot be deleted (I chown'd it to a different user and chmod'd to 600)

How do I accomplish this?

Here's the script:

```<code>#!/bin/bash

MASTERDELETELIST="/Sandbox/masterlist.txt"

file=$MASTERDELETELIST

while IFS= read list

    do   # first DeleteMeList file

        let "NUMBER+=1"
        CATEGORY="CATEGORY"
        REPORT="$CATEGORY-$NUMBER-REPORT"
        THISLOOPREPORT="/Sandbox/Dumpster/$REPORT-DELETEDFILES.txt"
        NOTFOUNDREPORT="/Sandbox/Dumpster/$REPORT-NOTFOUND.txt"
        ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"

        file=$list

        while IFS= read line

            do   #run the DeleteList items

                if [ -f  "$line" ]
                    then
                    # found the file
                    echo "$line" >> $THISLOOPREPORT
                    rm "$line"
                    # exec 2> ./Sandbox/Dumpster/errors.txt this works but doesn't update with each iteration reports
                    # exec 2> $ERRORSREPORT ???

                    else
                    echo "file not found: $line" >> $NOTFOUNDREPORT
                fi

            done < $list

    done < $MASTERDELETELIST
</code>```

答:
You should redirect the stderr with exec before you call commands that you want to be affected by this redirection, not after. In your case it would make most sense to place the exec just before the inner while loop. Also, you for logging you probably want to use appending redirection >>, otherwise the log file will get truncated on each iteration.

Example:

```<code>...
ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"
file=$list
exec 2>> "$ERRORSREPORT"
while IFS= read line; do
...
</code>```

Or as the commenter noted you can simply redirect the stderr of the inner loop, by adding the redirection after the done part, example:

```<code>done < $list 2>> "$ERRORSREPORT"
</code>```

Title: stderr out to a variable

Body:
I have a bash script that iterates through a list of file locations (filepath) and deletes them. I'd like to have any errors that the command throws (like permission issues) go to an individual log as it iterates through files. Like a confirmation that the delete actually happened.

So MASTERDELETELIST.txt has a list of DeleteMeList-Category-[A-Z].txt, each one then has lines like /foo/bar/deleteme-[01-99].txt (**brackets for illustration only)

As the script iterates, it creates a report specific to that CATEGORY list. I need to push it like so: exec 2> >> $ERRORSREPORT, which throws an error:

./script.sh: line 60: syntax error near unexpected token >>' ./script.sh: line 60:                  exec 2> >> $ERRORSREPORT'

*exact output from Terminal makes the formatting errors above)

..or exec 2> $ERRORREPORT which doesn't seem to output anything.. when a file cannot be deleted (I chown'd it to a different user and chmod'd to 600)

How do I accomplish this?

Here's the script:

#!/bin/bash

MASTERDELETELIST="/Sandbox/masterlist.txt"

file=$MASTERDELETELIST

while IFS= read list

    do   # first DeleteMeList file

        let "NUMBER+=1"
        CATEGORY="CATEGORY"
        REPORT="$CATEGORY-$NUMBER-REPORT"
        THISLOOPREPORT="/Sandbox/Dumpster/$REPORT-DELETEDFILES.txt"
        NOTFOUNDREPORT="/Sandbox/Dumpster/$REPORT-NOTFOUND.txt"
        ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"

        file=$list

        while IFS= read line

            do   #run the DeleteList items

                if [ -f  "$line" ]
                    then
                    # found the file
                    echo "$line" >> $THISLOOPREPORT
                    rm "$line"
                    # exec 2> ./Sandbox/Dumpster/errors.txt this works but doesn't update with each iteration reports
                    # exec 2> $ERRORSREPORT ???

                    else
                    echo "file not found: $line" >> $NOTFOUNDREPORT
                fi

            done < $list

    done < $MASTERDELETELIST

Body:
You should redirect the stderr with exec before you call commands that you want to be affected by this redirection, not after. In your case it would make most sense to place the exec just before the inner while loop. Also, you for logging you probably want to use appending redirection >>, otherwise the log file will get truncated on each iteration.

Example:

...
ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"
file=$list
exec 2>> "$ERRORSREPORT"
while IFS= read line; do
...

Or as the commenter noted you can simply redirect the stderr of the inner loop, by adding the redirection after the done part, example:

done < $list 2>> "$ERRORSREPORT"


问:
How to handle 401 error status code error in Node.js/Express?
I am working on login functionality in my project, now, flow looks like this (from front-end to back-end):

async login() {
  await login({
    password: this.userPassword,
    login: this.userLogin,
    twoFactor: this.twoFactor
  }).then((res) => {
    if (res.error) {
      //
    } else {
      console.log(res)
    }
  })
}
```
<p>And here is starts problems, as you can see if something goes wrong, I return status code 401 and some error message. When I login with correct data, there is no problem with getting token, but when I provide wrong data I have external pending <code>login</code> endpoint in development tools in browser and then, after some time, <code>Error: Request failed with status code 401</code> in front end terminal. Without this <code>status(401)</code> with just JSON it works fine, but when I try to add 401 code, application crashes.</p>
<pre class="lang-js prettyprint-override"><code>const userService = require('./../services/userService')
const crypto = require('./../services/cryptoService')
const jwt = require('./../services/jwtService')
const twoFactorService = require('node-2fa')

module.exports = {
  login: async (req, res) => {
    let { login, password, twoFactor } = req.body

    password = crypto.encrypt(password, process.env.APP_KEY)
    const result = await userService.getUserToLogin(login, password)

    if (!result) {
      res.status(401).json({
        error: 'Unauthorized'
      })
    } else {
      const faCode = result.twofatoken
      const result2F = twoFactorService.verifyToken(faCode, twoFactor);
      if ( !result2F || result2F.delta !== 0 ) {
        res.status(401).json({
          error: 'Unauthorized'
        })
      } else {
        const userId = crypto.encrypt(result.id, process.env.CRYPTO_KEY)
        const token = await jwt.sign({
          uxd: userId,
        });
        res.json(token);
      }
    }
  }
}
</code>```

Actually, I have no idea on what to do with that and how to handle this error.

答:
Ok, here is the answer. Actually, you just need to handle this error in your router:

router.post('/login', async (req, res) => {
  try {
    const data = await api.post('/login', req.body)
    res.json(data.data)
  } catch (e) {
    // Probably you have here just console.log(e), but this way, you can handle it
    res.status(e.response.status).json(e.response.data)
  }
})
```

Body:
I am working on login functionality in my project, now, flow looks like this (from front-end to back-end):

async login() {
  await login({
    password: this.userPassword,
    login: this.userLogin,
    twoFactor: this.twoFactor
  }).then((res) => {
    if (res.error) {
      //
    } else {
      console.log(res)
    }
  })
}

And here is starts problems, as you can see if something goes wrong, I return status code 401 and some error message. When I login with correct data, there is no problem with getting token, but when I provide wrong data I have external pending login endpoint in development tools in browser and then, after some time, Error: Request failed with status code 401 in front end terminal. Without this status(401) with just JSON it works fine, but when I try to add 401 code, application crashes.

const userService = require('./../services/userService')
const crypto = require('./../services/cryptoService')
const jwt = require('./../services/jwtService')
const twoFactorService = require('node-2fa')

module.exports = {
  login: async (req, res) => {
    let { login, password, twoFactor } = req.body

    password = crypto.encrypt(password, process.env.APP_KEY)
    const result = await userService.getUserToLogin(login, password)

    if (!result) {
      res.status(401).json({
        error: 'Unauthorized'
      })
    } else {
      const faCode = result.twofatoken
      const result2F = twoFactorService.verifyToken(faCode, twoFactor);
      if ( !result2F || result2F.delta !== 0 ) {
        res.status(401).json({
          error: 'Unauthorized'
        })
      } else {
        const userId = crypto.encrypt(result.id, process.env.CRYPTO_KEY)
        const token = await jwt.sign({
          uxd: userId,
        });
        res.json(token);
      }
    }
  }
}

Actually, I have no idea on what to do with that and how to handle this error.


问:
Python Map List of Strings to Integer List
Let's say I have a list

```<code>l = ['michael','michael','alice','carter']
</code>```

I want to map it to the following:

```<code>k = [1,1,2,3]
</code>```

Where michael corresponds to 1, alice corresponds to 2 etc. Is there a function in Python to do this easily?

答:
If you do not mind missing the mapping restriction, probably this is another good may to do it.

```<code>import numpy as np
names, tags = np.unique(l, return_inverse=True)

print(names)  # ['alice' 'carter' 'michael']
print(tags)   # [2, 2, 0, 1]
</code>```

Hope this can help in the future.

Body:
Let's say I have a list

l = ['michael','michael','alice','carter']

I want to map it to the following:

k = [1,1,2,3]

Where michael corresponds to 1, alice corresponds to 2 etc. Is there a function in Python to do this easily?

Body:
If you do not mind missing the mapping restriction, probably this is another good may to do it.

import numpy as np
names, tags = np.unique(l, return_inverse=True)

print(names)  # ['alice' 'carter' 'michael']
print(tags)   # [2, 2, 0, 1]

Hope this can help in the future.


问:
Convert Integers to Dollar Format in Oracle Database
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

```<code>SELECT value AS "Valuation" FROM estimates;
</code>```

Result:

Instead, I would like to show:

```<code>$115,508
$38,150
$92,832
$116,222
</code>```

How can I convert the integers into dollar $ format?

答:
Use to_char with extended parameters format and nlsparam: TO_CHAR (number)
and Number Format Models:

You can specify currency with NLS_CURRENCY and "Group symbol" (NLS_NUMERIC_CHARACTERS('dg'))

SELECT
   to_char(
       value
      ,'L999g999'
      ,q'[
          NLS_NUMERIC_CHARACTERS = '.,'
          NLS_CURRENCY = '$'
      ]') AS "Valuation"
FROM estimates;
```
<p>DBFiddle</p>
<p>Results:</p>
```         Valuation
           $11,234
              $104
          $321,349
            $2,837
```

NB: It's not necessary to specify extra NLS parameters if they correctly set on session level! So it will be much more agile and users will be able to use own session settings.

Body:
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

SELECT value AS "Valuation" FROM estimates;

Result:

Instead, I would like to show:

$115,508
$38,150
$92,832
$116,222

How can I convert the integers into dollar $ format?

Body:
Use to_char with extended parameters format and nlsparam: TO_CHAR (number)
and Number Format Models:

You can specify currency with NLS_CURRENCY and "Group symbol" (NLS_NUMERIC_CHARACTERS('dg'))

SELECT
   to_char(
       value
      ,'L999g999'
      ,q'[
          NLS_NUMERIC_CHARACTERS = '.,'
          NLS_CURRENCY = '$'
      ]') AS "Valuation"
FROM estimates;

DBFiddle

Results:

         Valuation
           $11,234
              $104
          $321,349
            $2,837

NB: It's not necessary to specify extra NLS parameters if they correctly set on session level! So it will be much more agile and users will be able to use own session settings.


问:
new Date(); in React causing loop and CRASH. why?
```<code>import React, { useState, useEffect } from "react";

import "./Date.css";
import "./Home.css";

export default function Date(props) {
  const [dateState, setDateState] = useState(new Date());
  useEffect(() => {
    setInterval(() => setDateState(new Date()), 30000);
  }, []);
  if (props.active) {
    return (
      <div className="Date popup">
        <p>TODAYS DATE WILL GO HERE</p>
        <p>
          {" "}
          {dateState.toLocaleDateString("en-GB", {
            day: "numeric",
            month: "short",
            year: "numeric",
          })}
        </p>
        <p>THE TIME WILL GO HERE HH:MM:SS</p>
        <p>
          {dateState.toLocaleString("en-US", {
            hour: "numeric",
            minute: "numeric",
            hour12: true,
          })}
        </p>
      </div>
    );
  } else return null;
}
</code>```

I am trying to implement the javascript Date() method in React and no matter what when I try it, it makes the app crash. I am getting an error in the console.

Uncaught RangeError: Maximum call stack size exceeded

Even if I try to do something simple like below, it still crashes.

```<code>let now = new Date();
console.log(now)
</code>```

link to repo https://github.com/mariaalouisaa/3-in-1-react.git

Thanks in advance!

答:
You declare Date name for your function component.(that is same as JavaScript Date function name!) And you call it in your function component that is created an infinite loop!
Rename your function component.

Body:
import React, { useState, useEffect } from "react";

import "./Date.css";
import "./Home.css";

export default function Date(props) {
  const [dateState, setDateState] = useState(new Date());
  useEffect(() => {
    setInterval(() => setDateState(new Date()), 30000);
  }, []);
  if (props.active) {
    return (

TODAYS DATE WILL GO HERE

          {" "}
          {dateState.toLocaleDateString("en-GB", {
            day: "numeric",
            month: "short",
            year: "numeric",
          })}

THE TIME WILL GO HERE HH:MM:SS

          {dateState.toLocaleString("en-US", {
            hour: "numeric",
            minute: "numeric",
            hour12: true,
          })}

    );
  } else return null;
}

I am trying to implement the javascript Date() method in React and no matter what when I try it, it makes the app crash. I am getting an error in the console.

Uncaught RangeError: Maximum call stack size exceeded

Even if I try to do something simple like below, it still crashes.

let now = new Date();
console.log(now)

link to repo https://github.com/mariaalouisaa/3-in-1-react.git

Thanks in advance!