问:
How to set svg icon to background-image property in styled component
I'm trying to set the SVG icon as a background image in my styled component and it's working fine in the local environment, but on the server, it doesn't work. I assume the problem is in the path. Here is the code of what I've tried so far

```<code>const IconComponent = styled('span')`
 .rdtNext > span:after {
   visibility: visible;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   margin: auto;
   width: 13px;
   height: 10px;
   content: '';
   background-image: url('src/assets/svg/right_arrow.svg'); //this is with direct path and it doesn't work
 }
`;
</code>```

And also tried importing it at the top of the file and using it as a variable like this

```<code>import rightArrow from 'src/assets/svg/right_arrow.svg';

const IconComponent = styled('span')`
  .rdtNext > span:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 13px;
    height: 10px;
    content: '';
    background-image: url(${rightArrow});
  }
`;
</code>```

and also as a prop

```<code>import rightArrow from 'src/assets/svg/right_arrow.svg';

<IconComponent backgroundImage={rightArrow} />

const IconComponent = styled('span')<{backgroundImage}>`
  .rdtNext > span:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 13px;
    height: 10px;
    content: '';
    background-image: url(${(props) => props.backgroundImage});
  }
`;
</code>```

and none of the above works. What am I doing wrong and how can I achieve this? Thanks in advance!

---EDIT---
The 'right_arrow.svg' looks like this

```<code><svg width="13" height="10" viewBox="0 0 13 10" fill="none"
xmlns="http://www.w3.org/2000/svg">
  <path d="M11.47 5.06641L0.603027 5.06641" stroke="#707070"
   stroke-linecap="round"/>
  <path d="M11.8721 5.06641L7.44507 1.06641" stroke="#707070"
   stroke-linecap="round"/>
  <path d="M11.8721 5.06641L7.44507 9.06641" stroke="#707070"
   stroke-linecap="round"/>
</svg>
</code>```

Body:
I'm trying to set the SVG icon as a background image in my styled component and it's working fine in the local environment, but on the server, it doesn't work. I assume the problem is in the path. Here is the code of what I've tried so far

const IconComponent = styled('span')`
 .rdtNext > span:after {
   visibility: visible;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   margin: auto;
   width: 13px;
   height: 10px;
   content: '';
   background-image: url('src/assets/svg/right_arrow.svg'); //this is with direct path and it doesn't work
 }
`;

And also tried importing it at the top of the file and using it as a variable like this

import rightArrow from 'src/assets/svg/right_arrow.svg';

const IconComponent = styled('span')`
  .rdtNext > span:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 13px;
    height: 10px;
    content: '';
    background-image: url(${rightArrow});
  }
`;

and also as a prop

import rightArrow from 'src/assets/svg/right_arrow.svg';

<IconComponent backgroundImage={rightArrow} />

const IconComponent = styled('span')<{backgroundImage}>`
  .rdtNext > span:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 13px;
    height: 10px;
    content: '';
    background-image: url(${(props) => props.backgroundImage});
  }
`;

and none of the above works. What am I doing wrong and how can I achieve this? Thanks in advance!

---EDIT---
The 'right_arrow.svg' looks like this

<svg width="13" height="10" viewBox="0 0 13 10" fill="none"
xmlns="http://www.w3.org/2000/svg">
  <path d="M11.47 5.06641L0.603027 5.06641" stroke="#707070"
   stroke-linecap="round"/>
  <path d="M11.8721 5.06641L7.44507 1.06641" stroke="#707070"
   stroke-linecap="round"/>
  <path d="M11.8721 5.06641L7.44507 9.06641" stroke="#707070"
   stroke-linecap="round"/>
</svg>


来源: stackexchange

问:
Prepend a route in express - for testing in Jest
I have an express app. I am using Jest to test. I need to add express.json() to my app just for testing, I don't want this in the backend code at all. I tried this suggestion: https://stackoverflow.com/a/64289458/1057630

However, I kept getting the error layer.match is not a function.

Any clever way to prepend app.use(express.json) to my app, keeping in mind the app already has all the routes and is exported when it gets to the testing file.

I have tried prepending using this suggested method: https://stackoverflow.com/a/64289458/1057630
I have also tried slightly similar variations with no success.

ContentLicense: CC BY-SA 4.0


问:
An error on Hyperledger Fabric while setting up samples using curl.......curl28: Failed to connect
I've just started with fabric and I'm using it on ubuntu. I was following the instructions on https://hyperledger-fabric.readthedocs.io/en/release-2.2/install.html while trying to install the samples , I found this error.
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/bootstrap.sh| bash -s

curl: (28) Failed to connect to raw.githubusercontent.com port 443 after 129768 ms: Connection timed out

I've been trying to fix it for hours. It would be helpful if someone can help me through this..Thank you


问:
XMLType from Oracle Result set is not being fected and exits application without error
I have a query that creates XMLElement which gives "SYS.XMLType" as output. I tried to fetch the data using XMLType it exits when I try to cast as given on the oracle website.

dppSummaryps = (OraclePreparedStatement) connDb.prepareStatement(dppSummary);
System.out.println("Prepared Statement before bind variables set:\n\t" + dppSummaryps.toString());
dppSummaryps.setString(1, readTimeStart);
dppSummaryps.setString(2, readTimeEnd);
// System.out.println("uwjdpps.dppSummary() " + dppSummaryps.toString());
ResultSet rs = dppSummaryps.executeQuery();
OracleResultSet ors = (OracleResultSet) rs;
ResultSetMetaData mdata = rs.getMetaData();

if (mdata.getColumnType(1) == OracleTypes.OPAQUE
        && mdata.getColumnTypeName(1).compareTo("SYS.XMLTYPE") == 0) {
    // we know it is an XMLtype
    System.out.println("YEAH XMLTYPE: Column name = " + mdata.getColumnTypeName(1));
}
while (ors.next()) {

    // get the XMLType
    OPAQUE poxml = ors.getOPAQUE("XML");
    XMLType xmltype = (XMLType) poxml;
    // get the XML as a string...
    System.out.println(xmltype);
    // xml = (XMLType) rs.getObject(1);
    // dppSummaryType = rs.getString("XML");
    String result = IOUtils.toString(poxml.getStream());
    System.out.println(result);
    try {
        File targetFile = new File(FILE_PATH_XML + "test.xml");
        // OutputStream outStream = new OutputStream(targetFile);
        // outStream.write(result);

        // IOUtils.closeQuietly(outStream);
    } catch (Exception e) {
        String err = e.toString();
        System.out.println(err);
    }
```


问:
I'm unable to connect with DNS seed list format to Atlas but works with old string format
I recently moved from town and i have a different ISP. In my old house i used to connect to Atlas with

```<code>mongodb+srv://cluster0.wiiy6cz.mongodb.net/myFirstDatabase" --username <username>
</code>```

and now it's not working, i have my new public ip Whitelisted on Atlas and the error message is
pymongo.errors.ConfigurationError: The resolution lifetime expired after 21.123 seconds: Server 127.0.0.53 UDP port 53 answered The DNS operation timed out.

However, connection can be established with the old format string

```<code>mongodb://ac-tm89nv9-shard-00-00.wiiy6cz.mongodb.net:27017,ac-tm89nv9-shard-00-01.wiiy6cz.mongodb.net:27017,ac-tm89nv9-shard-00-02.wiiy6cz.mongodb.net:27017/myFirstDatabase?replicaSet=atlas-mqfpjp-shard-0" --ssl --authenticationDatabase admin --username <username> --password <password>
</code>```

The only thing different now is my Internet Provider so i think it has to be something with the configuration of the DNS.

I already have installed pymongo[srv], i checked DNS of router configuration which is  DNS1: 45.71.46.194 DNS2: 8.8.8.8 DNS3: 0.0.0.0

So i'm curious about what is the problem here, i have already find a way around, but i really wish to know what is happening here

Body:
I recently moved from town and i have a different ISP. In my old house i used to connect to Atlas with

mongodb+srv://cluster0.wiiy6cz.mongodb.net/myFirstDatabase" --username <username>

and now it's not working, i have my new public ip Whitelisted on Atlas and the error message is
pymongo.errors.ConfigurationError: The resolution lifetime expired after 21.123 seconds: Server 127.0.0.53 UDP port 53 answered The DNS operation timed out.

However, connection can be established with the old format string

mongodb://ac-tm89nv9-shard-00-00.wiiy6cz.mongodb.net:27017,ac-tm89nv9-shard-00-01.wiiy6cz.mongodb.net:27017,ac-tm89nv9-shard-00-02.wiiy6cz.mongodb.net:27017/myFirstDatabase?replicaSet=atlas-mqfpjp-shard-0" --ssl --authenticationDatabase admin --username <username> --password <password>

The only thing different now is my Internet Provider so i think it has to be something with the configuration of the DNS.

I already have installed pymongo[srv], i checked DNS of router configuration which is  DNS1: 45.71.46.194 DNS2: 8.8.8.8 DNS3: 0.0.0.0

So i'm curious about what is the problem here, i have already find a way around, but i really wish to know what is happening here


问:
How to convert JSON column in DataFrame to "normal" columns in DataFrame in Python Pandas?
I have DataFrame like below:

```<code>ABT = pd.read_excel("ABT.xlsx")
</code>```

DATA TYPES:

COL1 - float

COL2 - int

COL3 - object

COL1
COL2
COL3
COL4

1.2
5
{"X":"cc", "y":12}
{"A":{1,2}, "B":{3,3}"}

0.0
2
{"X":"dd", "y":13}
{"A":{0,1}, "B":{2,2}"}

2.22
0
{"X":"ee", "y":45}
{"A":{5,5}, "B":{1,1}"}

...
...
...
...

And I need to have something like below:

```<code>| COL1 | COL2| COL3               | X   | y   | A  | B
|------|-----|--------------------|-----|-----|----------
| 1.2  | 5   | {"X":"cc", "y":12} | cc  | 12  |
| 0.0  | 2   | {"X":"dd", "y":13} | dd  | 13  |
| 2.22 | 0   | {"X":"ee", "y":45} | ee  | 45  |
| ...  | ... | ...                | ... | ... |
</code>```

I tried to use code like below, but it does not work:
pd.json_normalize(ABT) because of error: AttributeError: 'str' object has no attribute 'values'

I also tried this one: pd.io.json.json_normalize(ABT.COL3[0]) but I have error: AttributeError: 'str' object has no attribute 'values'

How can I do that in Python Pandas ? I have a problem to image how should look output for values in COL4 ?

In my real DF:
When I use ABT.head().to_dict('list') I have liek below:

```<code>{'COL1': [0.0],
 'COL2': [2],
 'COL3': [2162561990],
 'COL4': [1500.0],
 'COL5': [750.0],
 'COL6': ['{"paAccounts": {"mySector": 4, "otherSectors": 10}}'],
 'COL7': ['{"grade": "CC"}']}
</code>```

Body:
I have DataFrame like below:

ABT = pd.read_excel("ABT.xlsx")

DATA TYPES:

COL1 - float

COL2 - int

COL3 - object

COL1
COL2
COL3
COL4

1.2
5
{"X":"cc", "y":12}
{"A":{1,2}, "B":{3,3}"}

0.0
2
{"X":"dd", "y":13}
{"A":{0,1}, "B":{2,2}"}

2.22
0
{"X":"ee", "y":45}
{"A":{5,5}, "B":{1,1}"}

...
...
...
...

And I need to have something like below:

| COL1 | COL2| COL3               | X   | y   | A  | B
|------|-----|--------------------|-----|-----|----------
| 1.2  | 5   | {"X":"cc", "y":12} | cc  | 12  |
| 0.0  | 2   | {"X":"dd", "y":13} | dd  | 13  |
| 2.22 | 0   | {"X":"ee", "y":45} | ee  | 45  |
| ...  | ... | ...                | ... | ... |

I tried to use code like below, but it does not work:
pd.json_normalize(ABT) because of error: AttributeError: 'str' object has no attribute 'values'

I also tried this one: pd.io.json.json_normalize(ABT.COL3[0]) but I have error: AttributeError: 'str' object has no attribute 'values'

How can I do that in Python Pandas ? I have a problem to image how should look output for values in COL4 ?

In my real DF:
When I use ABT.head().to_dict('list') I have liek below:

{'COL1': [0.0],
 'COL2': [2],
 'COL3': [2162561990],
 'COL4': [1500.0],
 'COL5': [750.0],
 'COL6': ['{"paAccounts": {"mySector": 4, "otherSectors": 10}}'],
 'COL7': ['{"grade": "CC"}']}


问:
Safari browser always sees an update to unchanged service worker
I've built a VueJS PWA and used register-service-worker to manage a service worker. I've built the app so when a new route is visited, it manually checks for an update to the service worker. If there is an update, it displays an alert to the user to refresh.

However, I'm experiencing a problem in Safari (both MacOS and iOS). While the update code works correctly, when visiting the web app in Safari it appears to constantly trigger the "update available" alert on every route change and refreshing doesn't seem to resolve the problem. It's as if Service Worker isn't get updated locally even though the web app shows the latest changes.

This is the code that manually checks on route changes:

router.beforeEach((to, from, next) => {

    navigator.serviceWorker.getRegistration(`${process.env.BASE_URL}service-worker.js`).then(reg => {
        // check for updates to the service working on change of route
        reg.update();
    });
});
```
<p>My <code>registerServiceWorker.js</code> then has then within the <code>updated</code> part which fires a custom event then there is an update to the service worker that the app can listen for:</p>
<pre class="lang-js prettyprint-override"><code>/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated (registration) {
        console.log('New content is available; please refresh.')
        document.dispatchEvent(
            new CustomEvent('swUpdated', { detail: registration })
        )
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

</code>```

My vue app then listens for "swUpdated" and displays alert to the user to refresh their browser if there is a new service worker.

...
document.addEventListener('swUpdated', this.updateAvailable, { once: true })
...
updateAvailable(event) {

   this.registration = event.detail
   this.showReloadDialog = true
},
...
```

Body:
I've built a VueJS PWA and used register-service-worker to manage a service worker. I've built the app so when a new route is visited, it manually checks for an update to the service worker. If there is an update, it displays an alert to the user to refresh.

However, I'm experiencing a problem in Safari (both MacOS and iOS). While the update code works correctly, when visiting the web app in Safari it appears to constantly trigger the "update available" alert on every route change and refreshing doesn't seem to resolve the problem. It's as if Service Worker isn't get updated locally even though the web app shows the latest changes.

This is the code that manually checks on route changes:

router.beforeEach((to, from, next) => {

    navigator.serviceWorker.getRegistration(`${process.env.BASE_URL}service-worker.js`).then(reg => {
        // check for updates to the service working on change of route
        reg.update();
    });
});

My registerServiceWorker.js then has then within the updated part which fires a custom event then there is an update to the service worker that the app can listen for:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated (registration) {
        console.log('New content is available; please refresh.')
        document.dispatchEvent(
            new CustomEvent('swUpdated', { detail: registration })
        )
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

My vue app then listens for "swUpdated" and displays alert to the user to refresh their browser if there is a new service worker.

...
document.addEventListener('swUpdated', this.updateAvailable, { once: true })
...
updateAvailable(event) {

   this.registration = event.detail
   this.showReloadDialog = true
},
...


问:
Curl init CodeIgniter fix
I have a project in CodeIgniter and I have an error with handle, I have investigated that PHP8 curl_init works as an object. Any way to fix it?</p>

Title: Curl init CodeIgniter fix


问:
Pygame - menu problem. Button only functions once - Why?
So i messing round with pygame because i have an assignment at uni of building a connect 4 game. And so i have it done, so i was trying to make a menu for it. And my problem is, when i click the "JOGAR MULTIPLAYER"(portugues for playing multiplayer) the game starts, and then i have the code for it after 3s return to the main menu. BUT this time, the button "JOGAR MULTIPLAYER" does nothing, it does not show the game again. This is driving me crazyyyyy

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

def play():
while True:
import jogo

```<code>    jogo

    if jogo.fim_de_jogo:
        pygame.time.wait(3000)
        menu_princ()

    pygame.display.update()
</code>```

def menu_princ():
#Menu Principal
while True:
WINDOW.blit(BG, (0,0)) #blit - Block Transfer - copia os conteúdos de uma surface/window para outra

```<code>    pos_mouse = pygame.mouse.get_pos() #get a posição do cursos do mouse
    text_menu = font(75).render("MENU", True, "#f873a2")
    rect_menu = text_menu.get_rect(center=(350, 75))

    play_button = Button(image=pygame.transform.scale(BG_PLAY_BUTTON,(570,109) ), pos=(350, 250), text_input="JOGAR MULTIPLAYER", font=font(30), base_color="#d7fcd4", hovering_color="White")
    ai_button = Button(image=pygame.transform.scale(BG_AI_BUTTON,(550,109) ), pos=(350, 400), text_input="JOGAR CONTRA AI", font=font(30), base_color="#d7fcd4", hovering_color="White")
    exit_button = Button(image=pygame.transform.scale(BG_EXIT_BUTTON,(195,109) ), pos=(350, 550), text_input="SAIR", font=font(30), base_color="#d7fcd4", hovering_color="White")

    WINDOW.blit(text_menu,rect_menu)

    for button in [play_button, ai_button, exit_button]:
        button.changeColor(pos_mouse)
        button.update(WINDOW)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if play_button.checkForInput(pos_mouse): #se o input for no botão do "JOGAR" - começa o jogo multiplayer
                play()
            #if ai_button.checkForInput(pos_mouse): #se o input for no botão do "JOGAR CONTRA AI" - começa o jogo contra AI
                #play_ai()
            if exit_button.checkForInput(pos_mouse): #se o input for no botão do "SAIR" - a janela fecha-se/jogo encerra
                pygame.quit()
                sys.exit()

    pygame.display.update()
</code>```

menu_princ()

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

def play() is the function i use to import the game code
and the def menu_princ() is the function i use to create the main menu, and the play_button is the button that is not working( it is the 1st button)

I have try everything that i have learned till the moment and can't fix it :(

Body:
So i messing round with pygame because i have an assignment at uni of building a connect 4 game. And so i have it done, so i was trying to make a menu for it. And my problem is, when i click the "JOGAR MULTIPLAYER"(portugues for playing multiplayer) the game starts, and then i have the code for it after 3s return to the main menu. BUT this time, the button "JOGAR MULTIPLAYER" does nothing, it does not show the game again. This is driving me crazyyyyy

def play():
while True:
import jogo

    jogo

    if jogo.fim_de_jogo:
        pygame.time.wait(3000)
        menu_princ()

    pygame.display.update()

def menu_princ():
#Menu Principal
while True:
WINDOW.blit(BG, (0,0)) #blit - Block Transfer - copia os conteúdos de uma surface/window para outra

    pos_mouse = pygame.mouse.get_pos() #get a posição do cursos do mouse
    text_menu = font(75).render("MENU", True, "#f873a2")
    rect_menu = text_menu.get_rect(center=(350, 75))

    play_button = Button(image=pygame.transform.scale(BG_PLAY_BUTTON,(570,109) ), pos=(350, 250), text_input="JOGAR MULTIPLAYER", font=font(30), base_color="#d7fcd4", hovering_color="White")
    ai_button = Button(image=pygame.transform.scale(BG_AI_BUTTON,(550,109) ), pos=(350, 400), text_input="JOGAR CONTRA AI", font=font(30), base_color="#d7fcd4", hovering_color="White")
    exit_button = Button(image=pygame.transform.scale(BG_EXIT_BUTTON,(195,109) ), pos=(350, 550), text_input="SAIR", font=font(30), base_color="#d7fcd4", hovering_color="White")

    WINDOW.blit(text_menu,rect_menu)

    for button in [play_button, ai_button, exit_button]:
        button.changeColor(pos_mouse)
        button.update(WINDOW)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if play_button.checkForInput(pos_mouse): #se o input for no botão do "JOGAR" - começa o jogo multiplayer
                play()
            #if ai_button.checkForInput(pos_mouse): #se o input for no botão do "JOGAR CONTRA AI" - começa o jogo contra AI
                #play_ai()
            if exit_button.checkForInput(pos_mouse): #se o input for no botão do "SAIR" - a janela fecha-se/jogo encerra
                pygame.quit()
                sys.exit()

    pygame.display.update()

menu_princ()

def play() is the function i use to import the game code
and the def menu_princ() is the function i use to create the main menu, and the play_button is the button that is not working( it is the 1st button)

I have try everything that i have learned till the moment and can't fix it :(


问:
jaxb2 generated class from main xsd and common xsd has different namespaces
I have 2 xsd schemas from which Im generating a class Message using maven-jaxb2-plugin. The main xsd is message.xsd and it imports common.xsd which holds some common types. However both have different target namespaces.

This results in jaxb xml unmarshaller not reading the fields in the xml and using the default values. If in the generated class I manually set the namespace to "message" it works. Is there a way to place both generated class fields under the same namespace? Or perhaps is my XML message wrong? Or am I missing a jaxb2 generator parameter somewhere? Should I use a jaxb binding to solve this?

I cannot change the xsd namespace definitions. A lot of answers are so very close to what I need but none are the actual issue I have.

This generates a Message class that looks sort of like this:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "computer"
})
@XmlRootElement(name = "message", namespace = "message")
public class Message implements ToString2
{
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "date",
        "info"
    })
    public static class Computer implements ToString2
    {
    @XmlElement(namespace = "message", required = true)
        protected int date;
        @XmlElement(name = "info", namespace = "message", required = true)
        protected InfoType info;
    }
}
</code>```

The Info class is generated from the common.xsd and it looks like this:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InfoType", propOrder = {
    "number",
    "id"
})
public class InfoType implements ToString2
{

    @XmlElement(namespace = "")
    @XmlSchemaType(name = "integer")
    protected int number;
    @XmlElement(namespace = "")
    @XmlSchemaType(name = "integer")
    protected int id;
}
</code>```

I send this xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<message xmlns="message">
    <computer>
        <info>
            <name>2</name>
            <id>999998</id>
        </info>
        <date>20220508</date>
    </computer>
</message>
</code>```

package-info.java has the namespace set to "common" which is why I assume the namespace on the fields in Info are "" it looks like this:

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "common", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.myapp.message
</code>```

pom:

```<code><plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <version>0.14.0</version>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.3</version>
        </dependency>
    </dependencies>
    <configuration>
        <accessExternalSchema>all</accessExternalSchema>
        <specVersion>2.1</specVersion>
        <cleanPackageDirectories>false</cleanPackageDirectories>
        <extension>true</extension>
        <args>
            <arg>-Xfluent-api</arg>
            <arg>-XtoString</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>net.java.dev.jaxb2-commons</groupId>
                <artifactId>jaxb-fluent-api</artifactId>
                <version>${maven-jaxb2-plugin.fluent-api.version}</version>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-basics</artifactId>
                <version>${jaxb2-basics-runtime.version}</version>
            </plugin>
        </plugins>
    </configuration>
    <executions>
        <execution>
            <id>generate-message</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <schemaDirectory>src/main/resources/message</schemaDirectory>
                <schemaIncludes>
                    <include>message.xsd</include>
                </schemaIncludes>
                <bindingDirectory>src/main/resources/jaxb</bindingDirectory>
                <generateDirectory>target/generated-sources/jaxb/message</generateDirectory>
                <generatePackage>com.myapp.message
                </generatePackage>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

From other xsd generations I assume changing targetNamespace to the same namespace and using include instead of import would do the trick, however that is not an option.

Manually changing namespace in the @XmlElement(namespace = "") solves the problem, however that doesn't do much for me as it will get written over on the next generation.

I tried looking into xjb. However Im unsure if that is actually the way, if I set it to bind to the top element it has trouble resolving types from the commons.xsd - might be worth pursing?

Body:
I have 2 xsd schemas from which Im generating a class Message using maven-jaxb2-plugin. The main xsd is message.xsd and it imports common.xsd which holds some common types. However both have different target namespaces.

This results in jaxb xml unmarshaller not reading the fields in the xml and using the default values. If in the generated class I manually set the namespace to "message" it works. Is there a way to place both generated class fields under the same namespace? Or perhaps is my XML message wrong? Or am I missing a jaxb2 generator parameter somewhere? Should I use a jaxb binding to solve this?

I cannot change the xsd namespace definitions. A lot of answers are so very close to what I need but none are the actual issue I have.

This generates a Message class that looks sort of like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "computer"
})
@XmlRootElement(name = "message", namespace = "message")
public class Message implements ToString2
{
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "date",
        "info"
    })
    public static class Computer implements ToString2
    {
    @XmlElement(namespace = "message", required = true)
        protected int date;
        @XmlElement(name = "info", namespace = "message", required = true)
        protected InfoType info;
    }
}

The Info class is generated from the common.xsd and it looks like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InfoType", propOrder = {
    "number",
    "id"
})
public class InfoType implements ToString2
{

    @XmlElement(namespace = "")
    @XmlSchemaType(name = "integer")
    protected int number;
    @XmlElement(namespace = "")
    @XmlSchemaType(name = "integer")
    protected int id;
}

I send this xml:

<?xml version="1.0" encoding="utf-8"?>
<message xmlns="message">
    <computer>
        <info>
            <name>2</name>
            <id>999998</id>
        </info>
        <date>20220508</date>
    </computer>
</message>

package-info.java has the namespace set to "common" which is why I assume the namespace on the fields in Info are "" it looks like this:

@javax.xml.bind.annotation.XmlSchema(namespace = "common", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.myapp.message

pom:

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <version>0.14.0</version>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.3</version>
        </dependency>
    </dependencies>
    <configuration>
        <accessExternalSchema>all</accessExternalSchema>
        <specVersion>2.1</specVersion>
        <cleanPackageDirectories>false</cleanPackageDirectories>
        <extension>true</extension>
        <args>
            <arg>-Xfluent-api</arg>
            <arg>-XtoString</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>net.java.dev.jaxb2-commons</groupId>
                <artifactId>jaxb-fluent-api</artifactId>
                <version>${maven-jaxb2-plugin.fluent-api.version}</version>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-basics</artifactId>
                <version>${jaxb2-basics-runtime.version}</version>
            </plugin>
        </plugins>
    </configuration>
    <executions>
        <execution>
            <id>generate-message</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <schemaDirectory>src/main/resources/message</schemaDirectory>
                <schemaIncludes>
                    <include>message.xsd</include>
                </schemaIncludes>
                <bindingDirectory>src/main/resources/jaxb</bindingDirectory>
                <generateDirectory>target/generated-sources/jaxb/message</generateDirectory>
                <generatePackage>com.myapp.message
                </generatePackage>
            </configuration>
        </execution>
    </executions>
</plugin>

From other xsd generations I assume changing targetNamespace to the same namespace and using include instead of import would do the trick, however that is not an option.

Manually changing namespace in the @XmlElement(namespace = "") solves the problem, however that doesn't do much for me as it will get written over on the next generation.

I tried looking into xjb. However Im unsure if that is actually the way, if I set it to bind to the top element it has trouble resolving types from the commons.xsd - might be worth pursing?


问:
Heroku n8n app update failure : How do I update my n8n version on Heroku?

Describe the issue/error/question

n8n was deployed on my company Heroku as a separate app a year ago. Since then it's not been updated.
Last week Heroku stoped providing free postgre DB so we lost our workflows.

I was able to recover the database and our workflow however I cannot update n8n to the current version.

What is the error message (if any)?

When I type npm list -g:

corepack @0.10.0

n8n@0.153.0

npm @8.1.2

I see that my n8n is version 0.153.0. The most recent version is 0.208.1 (which enables for private app key from Hubspot).

I used npm update -g n8n to update my version, here's what I think are the main parts of the log:

! >! (node:3) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification. ! >! (Use node --trace-warnings ...to show where the warning was created) ! >! added 534 packages, removed 136 packages, changed 808 packages, and audited 1343 packages in 5m ! >! 121 packages are looking for funding runnpm fundfor details ! >! 13 vulnerabilities (8 moderate, 5 high) ! >! To address issues that do not require attention, run: npm audit fix ! >! To address all issues possible (including breaking changes), run: npm audit fix --force ! >! Some issues need review, and may require choosing a different dependency. ! >! Runnpm auditfor details. npm notice npm notice New major version of npm available! 8.1.2 -\> 9.2.0 npm notice Changelog: https://github.com/npm/cli/releases/tag/v9.2.0 npm notice Run npm install -g npm@9.2.0 to update! npm notice !
I tried running npm install -g npm@9.2.0 and npm update -g npm to no avail.

When I run npm list -g I see that none of my depencies are updated.

Information on your n8n setup

n8n version: 0.153.00

Database you're using: Heroku PostGre Mini

Running n8n with the execution process: default

Running n8n via : npm on Heroku

Happy Holidays and thanks to whomever might push me a clue on this ;)

I tried updating the app following the information I found on n8n doc, contacting heroku support and looking at related questions on stack overflow.

I expected to be able to update my version of n8n.


问:
Shape issue in post-hoc explainability method RISE
I'm trying to produce some results with post-hoc explainability method RISE link. For this I used a ResNet34 model trained on my custom dataset without pretrained weights. The input for this is (560, 560, 1), so the images are greyscale with size 560x560.

Somehow, Rise expects to have RGB images while the input image + model has the same greyscale shape.Does anyone know wheter RISE can only be used with RGB images or how to solve this problem?

It seems that in easy_start_ipybn (RISE) before getting fed into def generate_masks the images get resshaped into (560, 560, 3)

Running

sal = explain(model, x, masks)

provides this error:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-24-cf56f9bf1828> in <module>
----> 1 sal = explain(model, x, masks)

3 frames
/usr/local/lib/python3.8/dist-packages/keras/engine/training.py in tf__predict_function(iterator)
     13                 try:
     14                     do_return = True
---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
     16                 except:
     17                     do_return = False

ValueError: in user code:

    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1845, in predict_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1834, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1823, in run_step  **
        outputs = model.predict_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1791, in predict_step
        return self(x, training=False)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None

    ValueError: Exception encountered when calling layer "res_net_type_i" (type ResNetTypeI).

    Could not find matching concrete function to call loaded from the SavedModel. Got:
      Positional arguments (3 total):
        * <tf.Tensor 'inputs:0' shape=(None, 560, 560, 3) dtype=float32>
        * False
        * None
      Keyword arguments: {}

     Expected these arguments to match one of the following 4 option(s):

    Option 1:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='inputs')
        * False
        * None
      Keyword arguments: {}

    Option 2:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='inputs')
        * True
        * None
      Keyword arguments: {}

    Option 3:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='input_1')
        * False
        * None
      Keyword arguments: {}

    Option 4:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='input_1')
        * True
        * None
      Keyword arguments: {}

    Call arguments received by layer "res_net_type_i" (type ResNetTypeI):
      • args=('tf.Tensor(shape=(None, 560, 560, 3), dtype=float32)',)
      • kwargs={'training': 'False'}
</code>```

Body:
I'm trying to produce some results with post-hoc explainability method RISE link. For this I used a ResNet34 model trained on my custom dataset without pretrained weights. The input for this is (560, 560, 1), so the images are greyscale with size 560x560.

Somehow, Rise expects to have RGB images while the input image + model has the same greyscale shape.Does anyone know wheter RISE can only be used with RGB images or how to solve this problem?

It seems that in easy_start_ipybn (RISE) before getting fed into def generate_masks the images get resshaped into (560, 560, 3)

Running

sal = explain(model, x, masks)

provides this error:

ValueError                                Traceback (most recent call last)
<ipython-input-24-cf56f9bf1828> in <module>
----> 1 sal = explain(model, x, masks)

3 frames
/usr/local/lib/python3.8/dist-packages/keras/engine/training.py in tf__predict_function(iterator)
     13                 try:
     14                     do_return = True
---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
     16                 except:
     17                     do_return = False

ValueError: in user code:

    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1845, in predict_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1834, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1823, in run_step  **
        outputs = model.predict_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1791, in predict_step
        return self(x, training=False)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None

    ValueError: Exception encountered when calling layer "res_net_type_i" (type ResNetTypeI).

    Could not find matching concrete function to call loaded from the SavedModel. Got:
      Positional arguments (3 total):
        * <tf.Tensor 'inputs:0' shape=(None, 560, 560, 3) dtype=float32>
        * False
        * None
      Keyword arguments: {}

     Expected these arguments to match one of the following 4 option(s):

    Option 1:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='inputs')
        * False
        * None
      Keyword arguments: {}

    Option 2:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='inputs')
        * True
        * None
      Keyword arguments: {}

    Option 3:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='input_1')
        * False
        * None
      Keyword arguments: {}

    Option 4:
      Positional arguments (3 total):
        * TensorSpec(shape=(None, 560, 560, 1), dtype=tf.float32, name='input_1')
        * True
        * None
      Keyword arguments: {}

    Call arguments received by layer "res_net_type_i" (type ResNetTypeI):
      • args=('tf.Tensor(shape=(None, 560, 560, 3), dtype=float32)',)
      • kwargs={'training': 'False'}


问:
Syntax issue with Powershell Script
Good afternoon. I have been through many iterations of the script below:

`

```<code>$Path = "C:\Users"
$ExcludedUsers = "Default", "Public", "Administrator"
$Targetdate = (get-date).AddDays(-30)
$UserFolders = $Path | Get-ChildItem -Directory -Exclude $ExcludedUsers |where-object {$_.LastWriteTime -lt ($targetdate)} | select-object Name

#gets computer space before cleanup
$before = get-volume -driveletter c | select-object SizeRemaining

#DELETETHEPROFILES
foreach($User in $userFolders)
{   get-ciminstance -classname win32_userprofile -Property LocalPath | Where-object ($_.LocalPath -like '*$User.Name') | remove-ciminstance -whatif
}

#gets computer space after cleanup

$after = get-volume -driveletter c | select-object SizeRemaining
#calculates space freed

$freed = ($before.SizeRemaining - $after.SizeRemaining)*(0.000000001)
</code>```

`

$userfolders pulls a list of usernames and I'm trying to use that list to run remove-ciminstance to delete the profiles etc.

$_.LocalPath is in format "c:\users\username" I'm trying to point it to each profile in the $userFolders variable.

Now it runs great if i replace  Where-object ($.LocalPath -like '*$User.Name')  with Where-Object ($.LocalPath -like 'an actual username from the $Userfolders variable). Deleted the profile and life's great, but the minute i replace that with the foreach part *$User.Name it doesn't delete folder and doesn't throw an error, just does nothing.

I'm pretty sure i'm not using proper syntax and that's why i get a problem with the *$User.Name, but not sure what i should be using.

I just can't get the syntax right to find each username in a variable and delete it.

Title: Syntax issue with Powershell Script

Body:
Good afternoon. I have been through many iterations of the script below:

`

$Path = "C:\Users"
$ExcludedUsers = "Default", "Public", "Administrator"
$Targetdate = (get-date).AddDays(-30)
$UserFolders = $Path | Get-ChildItem -Directory -Exclude $ExcludedUsers |where-object {$_.LastWriteTime -lt ($targetdate)} | select-object Name

#gets computer space before cleanup
$before = get-volume -driveletter c | select-object SizeRemaining

#DELETETHEPROFILES
foreach($User in $userFolders)
{   get-ciminstance -classname win32_userprofile -Property LocalPath | Where-object ($_.LocalPath -like '*$User.Name') | remove-ciminstance -whatif
}

#gets computer space after cleanup

$after = get-volume -driveletter c | select-object SizeRemaining
#calculates space freed

$freed = ($before.SizeRemaining - $after.SizeRemaining)*(0.000000001)

`

$userfolders pulls a list of usernames and I'm trying to use that list to run remove-ciminstance to delete the profiles etc.

$_.LocalPath is in format "c:\users\username" I'm trying to point it to each profile in the $userFolders variable.

Now it runs great if i replace  Where-object ($.LocalPath -like '*$User.Name')  with Where-Object ($.LocalPath -like 'an actual username from the $Userfolders variable). Deleted the profile and life's great, but the minute i replace that with the foreach part *$User.Name it doesn't delete folder and doesn't throw an error, just does nothing.

I'm pretty sure i'm not using proper syntax and that's why i get a problem with the *$User.Name, but not sure what i should be using.

I just can't get the syntax right to find each username in a variable and delete it.


问:
Capacitor/push-notifications - Android receives the notification but does not open the APP when tap at the notification
Considering as an initial situation that the application is closed, the device receives the notification normally, but does not open the application when tap at the notification.
That is, it does not execute what was defined in 'pushNotificationActionPerformed'.
When the APP is opened the notification working ok ( 'pushNotificationReceived' is listened).

My code:

capacitor.config.js:

```<code>    PushNotifications: {
      "presentationOptions": ["badge", "sound", "alert"]
    },
</code>```

notification-app.service.ts:

```<code>import { Injectable, NgZone } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { ActionPerformed, PushNotifications, PushNotificationSchema, Token } from '@capacitor/push-notifications';

import { INotificacaoApp } from '../interfaces/INotificacaoApp';

@Injectable({
  providedIn: 'root'
})
export class NotificationAppService {

  _dadosNotificacao: INotificacaoApp;

  constructor(
    private zone: NgZone,
  ) { }

  async setupFCM() {
    if (Capacitor.getPlatform() == 'web') {
      return;
    } else {
      try {
        let permStatus = await PushNotifications.checkPermissions();
        if (permStatus) {
          if (permStatus.receive === 'prompt') {
            let permStatus2 = await PushNotifications.requestPermissions();
            if (permStatus2) {
              if (permStatus2.receive !== 'granted') {
                console.log('Notification not granted')
                return;
              } else {
                await PushNotifications.register();
              }
            }
          } else {
            if (permStatus.receive !== 'granted') {
              console.log('Notification not granted')
              return;
            } else {
              await PushNotifications.register();
            }
          }
        }

        PushNotifications.addListener(
          'registration',
          async (token: Token) => {
            console.log('My token: ' + JSON.stringify(token));
          }
        );

        PushNotifications.addListener('registrationError', async (error: any) => {
          console.log('Error no registro do token de notificacao: ' + JSON.stringify(error));
        });

        PushNotifications.addListener(
          'pushNotificationReceived',
          async (notification: PushNotificationSchema) => {
            this.zone.run(() => {
              if (notification.data
                && notification.data.dados) {
                this._dadosNotificacao = JSON.parse(notification.data.dados) as INotificacaoApp;
                console.log('recebeu notificacao')
                console.log(this._dadosNotificacao)
              }
            });
          }
        );

        PushNotifications.addListener(
          'pushNotificationActionPerformed',
          async (notification: ActionPerformed) => {
            console.log('Action performed: ' + JSON.stringify(notification.notification));
          }
        );

      } catch (err) {
        console.log(`SetupFCM com erro`)
      }
    }
  }

  async RemoveListeners() {
    PushNotifications.removeAllListeners();
  }

}
</code>```

The above setupFCM routine is called in tabs.page.ts

```<code>  constructor(
    private platform: Platform,
    private notificationAppService: NotificationAppService
  ) {
    this.platform.ready().then(async () => {
      this.notificationAppService.setupFCM();
    });
  }

</code>```

Versions:

npm: 9.1.1

node: 18.12.1

@capacitor/cli: 4.5.0

@capacitor/core: 4.5.0

@capacitor/android: 4.5.0

@capacitor/ios: 4.5.0

@capacitor/push-notifications: 4.1.2

@angular/core: 14.2.10

@ionic/angular: 6.3.7

@ionic/cli: 6.20.4

I tried several configuration adjustments, as shown in the files below:

In android/build.gradle: - added classpath for google-services:

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.2'
        classpath 'com.google.gms:google-services:4.3.14'
    }
}
</code>```

In android/app/build.gradle:
added google-services in plugins and added firebase-messaging dependency

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}
...
dependencies {
     ...
    implementation 'com.google.firebase:firebase-messaging:23.0.5'
}
</code>```

In variable.gradle: added firebaseMessagingVersion

```<code>ext {
    minSdkVersion = 22
    compileSdkVersion = 32
    targetSdkVersion = 32
    ...
    firebaseMessagingVersion = '23.0.5'
}
</code>```

The file google-services.json is in android/app directory.

Can someone help me?

Body:
Considering as an initial situation that the application is closed, the device receives the notification normally, but does not open the application when tap at the notification.
That is, it does not execute what was defined in 'pushNotificationActionPerformed'.
When the APP is opened the notification working ok ( 'pushNotificationReceived' is listened).

My code:

capacitor.config.js:

    PushNotifications: {
      "presentationOptions": ["badge", "sound", "alert"]
    },

notification-app.service.ts:

import { Injectable, NgZone } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { ActionPerformed, PushNotifications, PushNotificationSchema, Token } from '@capacitor/push-notifications';

import { INotificacaoApp } from '../interfaces/INotificacaoApp';

@Injectable({
  providedIn: 'root'
})
export class NotificationAppService {

  _dadosNotificacao: INotificacaoApp;

  constructor(
    private zone: NgZone,
  ) { }

  async setupFCM() {
    if (Capacitor.getPlatform() == 'web') {
      return;
    } else {
      try {
        let permStatus = await PushNotifications.checkPermissions();
        if (permStatus) {
          if (permStatus.receive === 'prompt') {
            let permStatus2 = await PushNotifications.requestPermissions();
            if (permStatus2) {
              if (permStatus2.receive !== 'granted') {
                console.log('Notification not granted')
                return;
              } else {
                await PushNotifications.register();
              }
            }
          } else {
            if (permStatus.receive !== 'granted') {
              console.log('Notification not granted')
              return;
            } else {
              await PushNotifications.register();
            }
          }
        }

        PushNotifications.addListener(
          'registration',
          async (token: Token) => {
            console.log('My token: ' + JSON.stringify(token));
          }
        );

        PushNotifications.addListener('registrationError', async (error: any) => {
          console.log('Error no registro do token de notificacao: ' + JSON.stringify(error));
        });

        PushNotifications.addListener(
          'pushNotificationReceived',
          async (notification: PushNotificationSchema) => {
            this.zone.run(() => {
              if (notification.data
                && notification.data.dados) {
                this._dadosNotificacao = JSON.parse(notification.data.dados) as INotificacaoApp;
                console.log('recebeu notificacao')
                console.log(this._dadosNotificacao)
              }
            });
          }
        );

        PushNotifications.addListener(
          'pushNotificationActionPerformed',
          async (notification: ActionPerformed) => {
            console.log('Action performed: ' + JSON.stringify(notification.notification));
          }
        );

      } catch (err) {
        console.log(`SetupFCM com erro`)
      }
    }
  }

  async RemoveListeners() {
    PushNotifications.removeAllListeners();
  }

}

The above setupFCM routine is called in tabs.page.ts

  constructor(
    private platform: Platform,
    private notificationAppService: NotificationAppService
  ) {
    this.platform.ready().then(async () => {
      this.notificationAppService.setupFCM();
    });
  }

Versions:

npm: 9.1.1

node: 18.12.1

@capacitor/cli: 4.5.0

@capacitor/core: 4.5.0

@capacitor/android: 4.5.0

@capacitor/ios: 4.5.0

@capacitor/push-notifications: 4.1.2

@angular/core: 14.2.10

@ionic/angular: 6.3.7

@ionic/cli: 6.20.4

I tried several configuration adjustments, as shown in the files below:

In android/build.gradle: - added classpath for google-services:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.2'
        classpath 'com.google.gms:google-services:4.3.14'
    }
}

In android/app/build.gradle:
added google-services in plugins and added firebase-messaging dependency

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}
...
dependencies {
     ...
    implementation 'com.google.firebase:firebase-messaging:23.0.5'
}

In variable.gradle: added firebaseMessagingVersion

ext {
    minSdkVersion = 22
    compileSdkVersion = 32
    targetSdkVersion = 32
    ...
    firebaseMessagingVersion = '23.0.5'
}

The file google-services.json is in android/app directory.

Can someone help me?


问:
Inertia JS - Vite application, Quasar installed, Quasar iconset installed, but not working. Seems impossible to make it working
In app.js:

```<code>import iconSet from 'quasar/icon-set/fontawesome-v6'
import '@quasar/extras/fontawesome-v6/fontawesome-v6.css'
</code>```

and:

```<code>setup({el, app, props, plugin}) {
    return createApp({render: () => h(app, props)})
        .use(plugin)
        .use(ZiggyVue, Ziggy)
        .use(PrimeVue)
        .use(Quasar,{iconSet: iconSet,})
        .mount(el);
},
</code>```

In template:

```<code><q-btn color="yellow" glossy text-color="black" push label="First" icon="fabAngular"/>
</code>```

The icon prop is not woking, it writes the name of icon instead of rendering it.
Anyone any idea what I am doing wrong?

I have tried it with different icon sets, but neither seems working. Icons are not rendering, only their names is written out.

Body:
In app.js:

import iconSet from 'quasar/icon-set/fontawesome-v6'
import '@quasar/extras/fontawesome-v6/fontawesome-v6.css'

and:

setup({el, app, props, plugin}) {
    return createApp({render: () => h(app, props)})
        .use(plugin)
        .use(ZiggyVue, Ziggy)
        .use(PrimeVue)
        .use(Quasar,{iconSet: iconSet,})
        .mount(el);
},

In template:

<q-btn color="yellow" glossy text-color="black" push label="First" icon="fabAngular"/>

The icon prop is not woking, it writes the name of icon instead of rendering it.
Anyone any idea what I am doing wrong?

I have tried it with different icon sets, but neither seems working. Icons are not rendering, only their names is written out.


问:
Python classes, mappings, pprint, KeysView vs. dict_keys; to keys() or not to keys()?
I have a problem with my base class. I started writing it after finding an answer on this site about more informative __repr__() methods. I added to it after finding a different answer on this site about using pprint() with my own classes. I tinkered with it a little more after finding a third answer on this site about making my classes unpackable with a ** operator.

I modified it again after seeing in yet another answer on this site that there was a distinction between merely giving it __getitem__(), __iter__(), and __len__() methods on the one hand, and actually making it a fully-qualified mapping by subclassing collections.abc.Mapping on the other. Further, I saw that doing so would remove the need for writing my own keys() method, as the Mapping would take care of that.

So I got rid of keys(), and a class method broke.

The problem

I have a method that iterates through my class' keys and values to produce one big string formatted as I'd like it. That class looks like this.

class MyObj():
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def the_problem_method(self):
        """Method I'm getting divergent output for."""
        longest = len(max((key for key in self.keys()), key=len))
        key_width = longest + TAB_WIDTH - longest % TAB_WIDTH
        return '\n'.join((f'{key:<{key_width}}{value}' for key, value in self))

```
<p>Yes, that doesn't have the base class in it, but the MWE later on will account for that. The nut of it is that <code>(key for key in self.keys())</code> part. When I have a <code>keys()</code> method written, I get the output I want.</p>
<pre class="lang-py prettyprint-override"><code>    def keys(self):
        """Get object attribute names."""
        return self.__dict__.keys()
</code>```

When I remove that to go with the keys() method supplied by collections.abc.Mapping, I get no space between key and value

The question

I can get the output I want by restoring the keys() method (and maybe adding values() and items() while I'm at it), but is that the best approach? Would it be better to go with the Mapping one and modify my class method to suit it? If so, how? Should I leave Mapping well enough alone until I know I need it?

This is my base class to be copied all aver creation and subclassed out the wazoo. I want to Get. It. Right.

There are already several considerations I can think of and many more of which I am wholly ignorant.

I use Python 3.9 and greater. I'll abandon 3.9 when conda does.

I want to keep my more-informative __repr__() methods.

I want pprint() to work, via the _dispatch table method with _format_dict_items().

I want to allow for duck typing my classes reliably.

I have not yet used type hinting, but I want to allow for using best practices there if I start.

Everything else I know nothing about.

The MWE

This has my problem class at the top and output stuff at the bottom. There are two series of classes building upon the previous ones.

The first are ever-more-inclusive base classes, and it is here that the difference between the instance with the keys() method and that without is shown. the class, BaseMap, subclasses the Mapping and has the __getitem__(), __iter__(), and __len__() methods. The next class up the chain, BaseMapKeys, subclasses that and adds the keys() method.

The second group, MapObj and MapKeysObj, are subclasses of the problem class that also subclass those different base classes respectively.

OK, maybe the WE isn't so M, but lots of things got me to this point and I don't want to neglect any.

import collections.abc
from pprint import pprint, PrettyPrinter

TAB_WIDTH = 3

class MyObj():
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def the_problem_method(self):
        """Method I'm getting divergent output for."""
        longest = len(max((key for key in self.keys()), key=len))
        key_width = longest + TAB_WIDTH - longest % TAB_WIDTH
        return '\n'.join((f'{key:<{key_width}}{value}' for key, value in self))

class Base(object):
    """Base class with more informative __repr__."""

    def __repr__(self):
        """Object representation."""
        params = (f'{key}={repr(value)}'
                  for key, value in self.__dict__.items())
        return f'{repr(self.__class__)}({", ".join(params)})'

class BaseMap(Base, collections.abc.Mapping):
    """Enable class to be pprint-able, unpacked with **."""

    def __getitem__(self, attr):
        """Get object attribute values."""
        return getattr(self.__dict__, attr)

    def __iter__(self):
        """Make object iterable."""
        for attr in self.__dict__.keys():
            yield attr, getattr(self, attr)

    def __len__(self):
        """Get length of object."""
        return len(self.__dict__)

class BaseMapKeys(BaseMap):
    """Overwrite KeysView output with what I thought it would be."""

    def keys(self):
        """Get object attribute names."""
        return self.__dict__.keys()

class MapObj(BaseMap, MyObj):
    """Problem class with collections.abc.Mapping."""

    def __init__(self, foo, bar):
        super().__init__(foo, bar)

class MapKeysObj(BaseMapKeys, MyObj):
    """Problem class with collections.abc.Mapping and keys method."""

    def __init__(self, foo, bar):
        super().__init__(foo, bar)

if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
    # assume the dispatch table method still works
    def pprint_basemap(printer, object, stream, indent, allowance, context,
                       level):
        """Implement pprint for subclasses of BaseMap class."""
        write = stream.write
        write(f'{object.__class__}(\n {indent * " "}')
        printer._format_dict_items(object, stream, indent, allowance + 1,
                                   context, level)
        write(f'\n{indent * " "})')
    map_classes = [MapObj, MapKeysObj]
    for map_class in map_classes:
        PrettyPrinter._dispatch[map_class.__repr__] = pprint_basemap

def print_stuff(map_obj):
    print('pprint object:')
    pprint(map_obj)
    print()
    print('print keys():')
    print(map_obj.keys())
    print()
    print('print list(keys()):')
    print(list(map_obj.keys()))
    print()
    print('print the problem method:')
    print(map_obj.the_problem_method())
    print('\n\n')

params = ['This is a really long line to force new line in pprint output', 2]
baz = MapObj(*params)
print_stuff(baz)
scoggs = MapKeysObj(*params)
print_stuff(scoggs)
```

Body:
I have a problem with my base class. I started writing it after finding an answer on this site about more informative __repr__() methods. I added to it after finding a different answer on this site about using pprint() with my own classes. I tinkered with it a little more after finding a third answer on this site about making my classes unpackable with a ** operator.

I modified it again after seeing in yet another answer on this site that there was a distinction between merely giving it __getitem__(), __iter__(), and __len__() methods on the one hand, and actually making it a fully-qualified mapping by subclassing collections.abc.Mapping on the other. Further, I saw that doing so would remove the need for writing my own keys() method, as the Mapping would take care of that.

So I got rid of keys(), and a class method broke.

The problem

I have a method that iterates through my class' keys and values to produce one big string formatted as I'd like it. That class looks like this.

class MyObj():
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def the_problem_method(self):
        """Method I'm getting divergent output for."""
        longest = len(max((key for key in self.keys()), key=len))
        key_width = longest + TAB_WIDTH - longest % TAB_WIDTH
        return '\n'.join((f'{key:<{key_width}}{value}' for key, value in self))

Yes, that doesn't have the base class in it, but the MWE later on will account for that. The nut of it is that (key for key in self.keys()) part. When I have a keys() method written, I get the output I want.

    def keys(self):
        """Get object attribute names."""
        return self.__dict__.keys()

When I remove that to go with the keys() method supplied by collections.abc.Mapping, I get no space between key and value

The question

I can get the output I want by restoring the keys() method (and maybe adding values() and items() while I'm at it), but is that the best approach? Would it be better to go with the Mapping one and modify my class method to suit it? If so, how? Should I leave Mapping well enough alone until I know I need it?

This is my base class to be copied all aver creation and subclassed out the wazoo. I want to Get. It. Right.

There are already several considerations I can think of and many more of which I am wholly ignorant.

I use Python 3.9 and greater. I'll abandon 3.9 when conda does.

I want to keep my more-informative __repr__() methods.

I want pprint() to work, via the _dispatch table method with _format_dict_items().

I want to allow for duck typing my classes reliably.

I have not yet used type hinting, but I want to allow for using best practices there if I start.

Everything else I know nothing about.

The MWE

This has my problem class at the top and output stuff at the bottom. There are two series of classes building upon the previous ones.

The first are ever-more-inclusive base classes, and it is here that the difference between the instance with the keys() method and that without is shown. the class, BaseMap, subclasses the Mapping and has the __getitem__(), __iter__(), and __len__() methods. The next class up the chain, BaseMapKeys, subclasses that and adds the keys() method.

The second group, MapObj and MapKeysObj, are subclasses of the problem class that also subclass those different base classes respectively.

OK, maybe the WE isn't so M, but lots of things got me to this point and I don't want to neglect any.

import collections.abc
from pprint import pprint, PrettyPrinter

TAB_WIDTH = 3

class MyObj():
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def the_problem_method(self):
        """Method I'm getting divergent output for."""
        longest = len(max((key for key in self.keys()), key=len))
        key_width = longest + TAB_WIDTH - longest % TAB_WIDTH
        return '\n'.join((f'{key:<{key_width}}{value}' for key, value in self))

class Base(object):
    """Base class with more informative __repr__."""

    def __repr__(self):
        """Object representation."""
        params = (f'{key}={repr(value)}'
                  for key, value in self.__dict__.items())
        return f'{repr(self.__class__)}({", ".join(params)})'

class BaseMap(Base, collections.abc.Mapping):
    """Enable class to be pprint-able, unpacked with **."""

    def __getitem__(self, attr):
        """Get object attribute values."""
        return getattr(self.__dict__, attr)

    def __iter__(self):
        """Make object iterable."""
        for attr in self.__dict__.keys():
            yield attr, getattr(self, attr)

    def __len__(self):
        """Get length of object."""
        return len(self.__dict__)

class BaseMapKeys(BaseMap):
    """Overwrite KeysView output with what I thought it would be."""

    def keys(self):
        """Get object attribute names."""
        return self.__dict__.keys()

class MapObj(BaseMap, MyObj):
    """Problem class with collections.abc.Mapping."""

    def __init__(self, foo, bar):
        super().__init__(foo, bar)

class MapKeysObj(BaseMapKeys, MyObj):
    """Problem class with collections.abc.Mapping and keys method."""

    def __init__(self, foo, bar):
        super().__init__(foo, bar)

if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
    # assume the dispatch table method still works
    def pprint_basemap(printer, object, stream, indent, allowance, context,
                       level):
        """Implement pprint for subclasses of BaseMap class."""
        write = stream.write
        write(f'{object.__class__}(\n {indent * " "}')
        printer._format_dict_items(object, stream, indent, allowance + 1,
                                   context, level)
        write(f'\n{indent * " "})')
    map_classes = [MapObj, MapKeysObj]
    for map_class in map_classes:
        PrettyPrinter._dispatch[map_class.__repr__] = pprint_basemap

def print_stuff(map_obj):
    print('pprint object:')
    pprint(map_obj)
    print()
    print('print keys():')
    print(map_obj.keys())
    print()
    print('print list(keys()):')
    print(list(map_obj.keys()))
    print()
    print('print the problem method:')
    print(map_obj.the_problem_method())
    print('\n\n')

params = ['This is a really long line to force new line in pprint output', 2]
baz = MapObj(*params)
print_stuff(baz)
scoggs = MapKeysObj(*params)
print_stuff(scoggs)


问:
Problem to log in at a postgreSQL database on AWS cloud
I have a server on AWS platform running an app. The database is on postgreSQL. The authentication is with .pem archives.
A few days ago, I was reported that the space of database was reaching the asigned quota, so I increase the quota through the RDS module on the cloud.
After doing it, I can't log in through pgAdmin to check the database. Nothing else was modified.

When I try to log in at the database I get this message:"Failed to create the SSH tunnel. Error: Could not establish session to SSH gateway"

The loggin configuration has always been like this (before increasing the quota I was able lo log in without any problems):
Use SSH tunneling: yes
Tunnel host: the IP assigned is the same and is still available.
Tunnel port: the port number is specified
Username: the username is specified
Authentication: Identity File
Identity file: It exist at the local route on my PC.

How can I fix this problem?

Thanks in advance.


问:
Argument of type Inventory is not assignable to parameter of type never
Creating an Ionic app from some tutorial and can not figure out what is wrong here. I got 2 messages about the code:

```<code>let a = item.payload.toJSON();
        a['$key'] = item.key;
        this.Bookings.push(a as Inventory);
</code>```

The messages are:

*- 'a' is possibly 'null'.

Argument of type 'Inventory' is not assignable to parameter of type 'never'.*

I tried to disable messages in the tsconfig.json file, messages are gone but it still is not working so somehow i have to solve this.

Body:
Creating an Ionic app from some tutorial and can not figure out what is wrong here. I got 2 messages about the code:

let a = item.payload.toJSON();
        a['$key'] = item.key;
        this.Bookings.push(a as Inventory);

The messages are:

*- 'a' is possibly 'null'.

Argument of type 'Inventory' is not assignable to parameter of type 'never'.*

I tried to disable messages in the tsconfig.json file, messages are gone but it still is not working so somehow i have to solve this.


问:
SVM Plot e1071 plots single color
I am trying to plot my SVM classification with usinf e1071 library.However, the classification plot shows only single value for my parameters.Even though I change the selected parameters to create 2d classification plot it is wrong.

```<code>require(caTools)
library(caret)

dataset <-read.csv("income_evaluation.csv")

# fnlwgt row remowed since it is not necessary
df_income <- subset(dataset,select=-c(fnlwgt))

# turn binary attribute into 0 and 1
df_income$income <-ifelse(df_income$income==" >50K",1,0)

df_income$native.country
apply(X=df_income,2,FUN=function(x) length(which(x==' ?')))

# handling missing values

#define function to calculate mode
find_mode <- function(x) {
  u <- unique(x)
  tab <- tabulate(match(x, u))
  u[tab == max(tab)]
}

mod_workclass_df  = find_mode(df_income$workclass)
mod_occupation_df  = find_mode(df_income$occupation)
mod_country_df  = find_mode(df_income$native.country)

# replacing the missing values with the mod values
df_income$workclass[df_income$workclass == ' ?'] <- mod_workclass_df
df_income$occupation[df_income$occupation == ' ?'] <- mod_occupation_df
df_income$native.country[df_income$native.country == ' ?'] <- mod_country_df

# one hot encoding for train set

dmy <- dummyVars(" ~ .", data = df_income, fullRank = T)
df_income <-  data.frame(predict(dmy, newdata = df_income))

# sampling
set.seed(101)
sample = sample.split(df_income$income, SplitRatio = .75)
trainingSet = subset(df_income, sample == TRUE)
testSet  = subset(df_income, sample == TRUE)

# isolaate y cariable
Y_train <- trainingSet$income
Y_test <- testSet$income

#isolate x cariable

X_test <- subset(testSet,select=-c(income))

# evalution of svm
library(e1071)
svm_classifier = svm(formula=income ~ .,data=trainingSet,type="C-classification",kernel="radial",scale=TRUE,cost=10)
Y_pred = predict(svm_classifier,newdata= X_test)
confusionMatrix(table(Y_test,Y_pred))

# cross validation

# in creating the folds we specify the target feature (dependent variable) and # of folds
folds = createFolds(trainingSet$income, k = 10)
# in cv we are going to applying a created function to our 'folds'
cv = lapply(folds, function(x) { # start of function
  # in the next two lines we will separate the Training set into it's 10 pieces
  training_fold = trainingSet[-x, ] # training fold =  training set minus (-) it's sub test fold
  test_fold = trainingSet[x, ] # here we describe the test fold individually
  # now apply (train) the classifer on the training_fold
  classifier = svm_classifier
  Y_pred = predict(svm_classifier,newdata= test_fold[-97])
  cm = table(test_fold[, 97], Y_pred)
  accuracy = (cm[1,1] + cm[2,2]) / (cm[1,1] + cm[2,2] + cm[1,2] + cm[2,1])
  return(accuracy)

  })
accuracy = mean(as.numeric(cv))
accuracy

trainingSet$income <-as.factor(trainingSet$income)

# Visualising the Training set results

plot(svm_classifier,trainingSet,education.num~age)

  library(ggplot2)
svm_classifier
table(predicted=svm_classifier$fitted,actual=trainingSet$income)
</code>```

Here is my code above and the plot below.I could not find the problem why there is only one color background and why there is any red color in the background.

Title: SVM Plot e1071 plots single color

Body:
I am trying to plot my SVM classification with usinf e1071 library.However, the classification plot shows only single value for my parameters.Even though I change the selected parameters to create 2d classification plot it is wrong.

require(caTools)
library(caret)

dataset <-read.csv("income_evaluation.csv")

# fnlwgt row remowed since it is not necessary
df_income <- subset(dataset,select=-c(fnlwgt))

# turn binary attribute into 0 and 1
df_income$income <-ifelse(df_income$income==" >50K",1,0)

df_income$native.country
apply(X=df_income,2,FUN=function(x) length(which(x==' ?')))

# handling missing values

#define function to calculate mode
find_mode <- function(x) {
  u <- unique(x)
  tab <- tabulate(match(x, u))
  u[tab == max(tab)]
}

mod_workclass_df  = find_mode(df_income$workclass)
mod_occupation_df  = find_mode(df_income$occupation)
mod_country_df  = find_mode(df_income$native.country)

# replacing the missing values with the mod values
df_income$workclass[df_income$workclass == ' ?'] <- mod_workclass_df
df_income$occupation[df_income$occupation == ' ?'] <- mod_occupation_df
df_income$native.country[df_income$native.country == ' ?'] <- mod_country_df

# one hot encoding for train set

dmy <- dummyVars(" ~ .", data = df_income, fullRank = T)
df_income <-  data.frame(predict(dmy, newdata = df_income))

# sampling
set.seed(101)
sample = sample.split(df_income$income, SplitRatio = .75)
trainingSet = subset(df_income, sample == TRUE)
testSet  = subset(df_income, sample == TRUE)

# isolaate y cariable
Y_train <- trainingSet$income
Y_test <- testSet$income

#isolate x cariable

X_test <- subset(testSet,select=-c(income))

# evalution of svm
library(e1071)
svm_classifier = svm(formula=income ~ .,data=trainingSet,type="C-classification",kernel="radial",scale=TRUE,cost=10)
Y_pred = predict(svm_classifier,newdata= X_test)
confusionMatrix(table(Y_test,Y_pred))

# cross validation

# in creating the folds we specify the target feature (dependent variable) and # of folds
folds = createFolds(trainingSet$income, k = 10)
# in cv we are going to applying a created function to our 'folds'
cv = lapply(folds, function(x) { # start of function
  # in the next two lines we will separate the Training set into it's 10 pieces
  training_fold = trainingSet[-x, ] # training fold =  training set minus (-) it's sub test fold
  test_fold = trainingSet[x, ] # here we describe the test fold individually
  # now apply (train) the classifer on the training_fold
  classifier = svm_classifier
  Y_pred = predict(svm_classifier,newdata= test_fold[-97])
  cm = table(test_fold[, 97], Y_pred)
  accuracy = (cm[1,1] + cm[2,2]) / (cm[1,1] + cm[2,2] + cm[1,2] + cm[2,1])
  return(accuracy)

  })
accuracy = mean(as.numeric(cv))
accuracy

trainingSet$income <-as.factor(trainingSet$income)

# Visualising the Training set results

plot(svm_classifier,trainingSet,education.num~age)

  library(ggplot2)
svm_classifier
table(predicted=svm_classifier$fitted,actual=trainingSet$income)

Here is my code above and the plot below.I could not find the problem why there is only one color background and why there is any red color in the background.


问:
How do I change color of selected TextInputEditText inside a Dialog and the positive and negative buttons text?
I am quite new to MaterialAlertDialogBuilder in android and I getting a purple default color for actively selected TextIputEditText. I need to change the color of inputs when active to my own color, say maybe teal or green... and also the color for the action buttons on the dialog.

Here below is some code:

```<code>package com.indupendo.landing.ui.dialogs;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.indupendo.R;
import com.indupendo.databinding.DialogLoginBinding;
import com.indupendo.globals.utilities.Utils;

public class LoginDialog extends DialogFragment {

    DialogLoginBinding binding;
    View view;

    public LoginDialog(View view) {
        this.view = view;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        binding = DialogLoginBinding.inflate(getLayoutInflater());
        MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(requireActivity(),
                R.style.MaterialAlertDialog_rounded);
        dialogBuilder.setView(binding.getRoot());

        dialogBuilder.setNegativeButton("Cancel", (dialog, which) -> {
            Utils.INSTANCE.showLoginCancellationSnackBar(view, getLayoutInflater());
            dialog.cancel();
        });

        dialogBuilder.setPositiveButton("Login", (dialog, which) -> Toast.makeText(
                getActivity(),
                "Logged In",
                Toast.LENGTH_LONG).show());

        return dialogBuilder.create();
    }

    @Override
    public void onCancel(@NonNull DialogInterface dialog) {
        super.onCancel(dialog);
        Utils.INSTANCE.showLoginCancellationSnackBar(view, getLayoutInflater());
        dialog.cancel();
    }
}
</code>```

Layout XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_login_dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login_dialog_title"
        android:textAlignment="center"
        android:textColor="@color/maroon"
        android:textSize="32sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_email_user_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:boxBackgroundColor="@android:color/transparent"
        app:startIconDrawable="@drawable/ic_baseline_email_24"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_login_dialog_title">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/ti_et_email_user_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="bottom"
            android:hint="@string/field_hint_email"
            android:inputType="textEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:boxBackgroundColor="@android:color/transparent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/til_email_user_id"
        app:startIconDrawable="@drawable/ic_baseline_lock_24"
        >

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/ti_et_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="bottom"
            android:hint="@string/field_hint_password" />
    </com.google.android.material.textfield.TextInputLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And here is the Theme

```<code><!--- Alert Dialog Theme -->
    <style name="MaterialAlertDialog_rounded" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="shapeAppearanceOverlay">@style/DialogCorners</item>
    </style>
</code>```

Body:
I am quite new to MaterialAlertDialogBuilder in android and I getting a purple default color for actively selected TextIputEditText. I need to change the color of inputs when active to my own color, say maybe teal or green... and also the color for the action buttons on the dialog.

Here below is some code:

package com.indupendo.landing.ui.dialogs;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.indupendo.R;
import com.indupendo.databinding.DialogLoginBinding;
import com.indupendo.globals.utilities.Utils;

public class LoginDialog extends DialogFragment {

    DialogLoginBinding binding;
    View view;

    public LoginDialog(View view) {
        this.view = view;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        binding = DialogLoginBinding.inflate(getLayoutInflater());
        MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(requireActivity(),
                R.style.MaterialAlertDialog_rounded);
        dialogBuilder.setView(binding.getRoot());

        dialogBuilder.setNegativeButton("Cancel", (dialog, which) -> {
            Utils.INSTANCE.showLoginCancellationSnackBar(view, getLayoutInflater());
            dialog.cancel();
        });

        dialogBuilder.setPositiveButton("Login", (dialog, which) -> Toast.makeText(
                getActivity(),
                "Logged In",
                Toast.LENGTH_LONG).show());

        return dialogBuilder.create();
    }

    @Override
    public void onCancel(@NonNull DialogInterface dialog) {
        super.onCancel(dialog);
        Utils.INSTANCE.showLoginCancellationSnackBar(view, getLayoutInflater());
        dialog.cancel();
    }
}

Layout XML:

<?xml version="1.0" encoding="UTF-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_login_dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login_dialog_title"
        android:textAlignment="center"
        android:textColor="@color/maroon"
        android:textSize="32sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_email_user_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:boxBackgroundColor="@android:color/transparent"
        app:startIconDrawable="@drawable/ic_baseline_email_24"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_login_dialog_title">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/ti_et_email_user_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="bottom"
            android:hint="@string/field_hint_email"
            android:inputType="textEmailAddress" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:boxBackgroundColor="@android:color/transparent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/til_email_user_id"
        app:startIconDrawable="@drawable/ic_baseline_lock_24"
        >

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/ti_et_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="bottom"
            android:hint="@string/field_hint_password" />
    </com.google.android.material.textfield.TextInputLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

And here is the Theme


问:
Sequelize - bulkInsert excluding an entry that already exists but showing what was excluded in reponse
I have got the partial answer to my question already with this answer (please check the question as well). But for my output I also want to know which entries were ignored. Is there any way to do that? So e.g using his input I somehow want to get that { name: 'John' } was ignored.


问:
React static deployment renders an empty page - React, Docker, NGINX, k8s Deployment
I started a react project using create-react-app and need to deploy it on our Kubernetes cluster. I am using Docker to create an image that runs npm run build and copies the build files to nginx. After deploying to a kubernetes cluster, the ingress endpoint renders a blank white empty page, no 404 errors. Here are some details:

On inspect element the page shows script tags within the  tag with the
 and
<link href="/static/css/main.9b9c3870.css" rel="stylesheet">
resources, however, the body contains empty root div

.
All HTTP calls return 200 status. All webpage routes lead to the same blank empty page.

NGINX Conf

```<code>server {
    listen 80;
    root  /usr/share/nginx/html;
    include /etc/nginx/mime.types;

    location / {
        index index.html index.htm
        try_files $uri $uri/ /index.html;
    }
}
</code>```

Dockerfile

```<code># Name the node stage "builder"
FROM node:14 AS builder

# Set working directory
WORKDIR /app

COPY package*.json /app/

RUN npm install

COPY ./ /app/

RUN npm run build

# nginx stage for serving content
FROM nginx:1.15

# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html

# Copy static assets from builder stage
COPY --from=builder /app/build .
COPY --from=builder /app/nginx/nginx.conf /etc/nginx/conf.d/

EXPOSE 80

# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]
</code>```

I tried the following steps as seen in many other stackoverflow answers:

homepage in package.json with values "https://companyendpoint.com" or "."

react-router basename with values {process.env.PUBLIC_URL}, "/", "/React"

Using HashRouter compared to BrowserRouter

Different configurations for nginx.conf

Body:
I started a react project using create-react-app and need to deploy it on our Kubernetes cluster. I am using Docker to create an image that runs npm run build and copies the build files to nginx. After deploying to a kubernetes cluster, the ingress endpoint renders a blank white empty page, no 404 errors. Here are some details:

On inspect element the page shows script tags within the  tag with the
 and
<link href="/static/css/main.9b9c3870.css" rel="stylesheet">
resources, however, the body contains empty root div

.
All HTTP calls return 200 status. All webpage routes lead to the same blank empty page.

NGINX Conf

server {
    listen 80;
    root  /usr/share/nginx/html;
    include /etc/nginx/mime.types;

    location / {
        index index.html index.htm
        try_files $uri $uri/ /index.html;
    }
}

Dockerfile

# Name the node stage "builder"
FROM node:14 AS builder

# Set working directory
WORKDIR /app

COPY package*.json /app/

RUN npm install

COPY ./ /app/

RUN npm run build

# nginx stage for serving content
FROM nginx:1.15

# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html

# Copy static assets from builder stage
COPY --from=builder /app/build .
COPY --from=builder /app/nginx/nginx.conf /etc/nginx/conf.d/

EXPOSE 80

# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

I tried the following steps as seen in many other stackoverflow answers:

homepage in package.json with values "https://companyendpoint.com" or "."

react-router basename with values {process.env.PUBLIC_URL}, "/", "/React"

Using HashRouter compared to BrowserRouter

Different configurations for nginx.conf


问:
posix headers under MINGW64
I am porting my C++ code from Linux to windows.
The code open a ttyACM*.
I am using MINGW64 for building code on Windows.
gcc generates an error that termios.h is not found.
Is there a MINGW64 library which supports Posix interfaces?
or should I switch to MSVC?</p>

Title: posix headers under MINGW64


问:
Generator raised StopIteration in find_job_titles package
I am trying to run this code:

```<code>from find_job_titles import FinderAcora
finder=FinderAcora()
</code>```
```<code>finder.findall('IT Audit & Governance')
</code>```

But it gives me this error everytime:

```<code>---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/find_job_titles/__init__.py in longest_match(matches)
     48     """
---> 49     longest = next(matches)
     50

StopIteration:

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
1 frames
<ipython-input-31-5b965ac3d7be> in <module>
----> 1 finder.findall('IT Audit & Governance')

/usr/local/lib/python3.8/dist-packages/find_job_titles/__init__.py in findall(self, string, use_longest)

     82                             else return all overlapping matches
     83         :returns: list of matches of type `Match`
---> 84         """
     85         return list(self.finditer(string, use_longest=use_longest))
     86

RuntimeError: generator raised StopIteration
</code>```

I tried using the suggestions from this Stack Overflow post but it didn't work.

Body:
I am trying to run this code:

from find_job_titles import FinderAcora
finder=FinderAcora()

finder.findall('IT Audit & Governance')

But it gives me this error everytime:

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/find_job_titles/__init__.py in longest_match(matches)
     48     """
---> 49     longest = next(matches)
     50

StopIteration:

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
1 frames
<ipython-input-31-5b965ac3d7be> in <module>
----> 1 finder.findall('IT Audit & Governance')

/usr/local/lib/python3.8/dist-packages/find_job_titles/__init__.py in findall(self, string, use_longest)

     82                             else return all overlapping matches
     83         :returns: list of matches of type `Match`
---> 84         """
     85         return list(self.finditer(string, use_longest=use_longest))
     86

RuntimeError: generator raised StopIteration

I tried using the suggestions from this Stack Overflow post but it didn't work.


问:
Google play store leaderboard not working
I added the Play Store services leaderboard and achievements to the game, the achievements section works, but the scoreboard does not work and I do not get any errors. When I click on the leaderboard button, the tables appear, but when I click on the tables, the loading screen stays and I cannot see the scores no matter how long I wait.
Also, I don't know if this info will help but in the build and shrink section
I marked them and these are my proguard rules

I'm very new to this stuff so I'm really having trouble solving a problem but I'm doing my best, I tried every way I can think of for this problem as well, tried different proguard rules I found, deleted the leaderboards and rebuilt them but it didn't work


问:
How can i create AAR with gradle dependencies locally in Android Studio?
Hi i just want to create AAR file from my library module locally.

I tried assemble its creating but the problem is its not including the other dependencies which i added in gradle. Is any idea or blog for solve this issue ?


问:
Generate Tailwind CSS in the browser
I have web app that allows users to enter their own HTML templates in Liquid, like a website builder. I'd like to allow my users to use Tailwind CSS in their custom templates, and then I would generate and save a compiled per-user CSS file based on the classes used in their custom template.

I understand I could do this using the Tailwind standalone executable on my server. But rather than have to manage a binary, I'd rather it just run in the browser since users create/edit their templates very rarely, and I'd persist the generated CSS. I'm also not generally using Tailwind in this app, I just want my users to be able to use it in their templates.

So basically, I'm wondering what the simplest way to use Tailwind in a JavaScript function where I can pass it some HTML and it will return generated CSS. Basically just what https://play.tailwindcss.com/ (source here) does with the "Generated CSS" pane.

Basically I'm looking for something like:

```

Is this possible?

Title: Generate Tailwind CSS in the browser

Body:
I have web app that allows users to enter their own HTML templates in Liquid, like a website builder. I'd like to allow my users to use Tailwind CSS in their custom templates, and then I would generate and save a compiled per-user CSS file based on the classes used in their custom template.

I understand I could do this using the Tailwind standalone executable on my server. But rather than have to manage a binary, I'd rather it just run in the browser since users create/edit their templates very rarely, and I'd persist the generated CSS. I'm also not generally using Tailwind in this app, I just want my users to be able to use it in their templates.

So basically, I'm wondering what the simplest way to use Tailwind in a JavaScript function where I can pass it some HTML and it will return generated CSS. Basically just what https://play.tailwindcss.com/ (source here) does with the "Generated CSS" pane.

Basically I'm looking for something like:

Is this possible?


问:
How to create a Double Sidebar in react
I want to create a double sidebar in react that is a sidebar that looks something like this

in which the icons are part of sidebar 1 and options keep changing like invoice dashboard etc keep changing in sidebar 2

currently I am using the react sidebar pro library(https://www.npmjs.com/package/react-pro-sidebar) but it only provides multilevel vertical nesting thus i am able to acheive something like this

so how do I create this double sidebar

Title: How to create a Double Sidebar in react


问:
VirtualKeyboard API not working in electron react application
I'm working on an electron project that's running a react application in its browser.
I'm trying to hide the keyboard for specific input fields that are handled manually.

I've tried using the VirtualKeyboard API.

```<code>navigator.virtualKeyboard.hide()
</code>```

This does not seem to work for me. My version from navigator.userAgent is.

```<code> Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.160 Electron/18.3.4 Safari/537.36
</code>```

According to this documentation it should work in Chrome.
https://developer.chrome.com/docs/web-platform/virtual-keyboard/

Body:
I'm working on an electron project that's running a react application in its browser.
I'm trying to hide the keyboard for specific input fields that are handled manually.

I've tried using the VirtualKeyboard API.

navigator.virtualKeyboard.hide()

This does not seem to work for me. My version from navigator.userAgent is.

 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.160 Electron/18.3.4 Safari/537.36

According to this documentation it should work in Chrome.
https://developer.chrome.com/docs/web-platform/virtual-keyboard/