问:
I can't connect to the socket.io in my chatroom app. GET /socket.io/socket.io.js 404
I am designing a chatroom app, and I find some difficulties.
It seems that my ejs did not get socket.io and main.js
The path of the file is correct, but the terminal shows 404. I don't know where is the mistake.

main.ejs

```<code>.......

<script
        src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.9.2/qs.min.js"
        integrity="sha256-TDxXjkAUay70ae/QJBEpGKkpVslXaHHayklIVglFRT4="
        crossorigin="anonymous"
></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/main.js"></script>
</body>
</html>

</code>```

terminal

```<code>POST /admin/main 200 57.085 ms - 1188
GET /socket.io/socket.io.js 404 15.696 ms - 993
GET /js/main.js 404 15.547 ms - 993
GET /stylesheets/style.css 304 2.854 ms - -
</code>```

server.js

```<code>const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/message');
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./utils/User');

const app = express();
const server = http.createServer(app);
const io  = socketio(server);

app.use(express.static(path.join(__dirname,'public')))

.....

const PORT = 3000 || precess.env.PORT;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
</code>```

main.js

```<code>...

const socket = io();

// Join chatroom
socket.emit('joinRoom', username);

// Message from server
socket.on('message', (message) => {
    console.log(message);
    outputMessage(message);

    // Scroll down
    chatMessages.scrollTop = chatMessages.scrollHeight;
});

// Message submit
chatForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // Get message text
    let msg = e.target.elements.msg.value;

    msg = msg.trim();

    if (!msg) {
        return false;
    }

    // Emit message to server
    socket.emit('chatMessage', msg);

    // Clear input
    e.target.elements.msg.value = '';
    e.target.elements.msg.focus();
});

 .....

</code>```

I want my ejs connect to socket and main.js. I just start to study js, so it is tricky for me. I really need some help.

Body:
I am designing a chatroom app, and I find some difficulties.
It seems that my ejs did not get socket.io and main.js
The path of the file is correct, but the terminal shows 404. I don't know where is the mistake.

main.ejs

.......

terminal

POST /admin/main 200 57.085 ms - 1188
GET /socket.io/socket.io.js 404 15.696 ms - 993
GET /js/main.js 404 15.547 ms - 993
GET /stylesheets/style.css 304 2.854 ms - -

server.js

const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/message');
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./utils/User');

const app = express();
const server = http.createServer(app);
const io  = socketio(server);

app.use(express.static(path.join(__dirname,'public')))

.....

const PORT = 3000 || precess.env.PORT;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

main.js

...

const socket = io();

// Join chatroom
socket.emit('joinRoom', username);

// Message from server
socket.on('message', (message) => {
    console.log(message);
    outputMessage(message);

    // Scroll down
    chatMessages.scrollTop = chatMessages.scrollHeight;
});

// Message submit
chatForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // Get message text
    let msg = e.target.elements.msg.value;

    msg = msg.trim();

    if (!msg) {
        return false;
    }

    // Emit message to server
    socket.emit('chatMessage', msg);

    // Clear input
    e.target.elements.msg.value = '';
    e.target.elements.msg.focus();
});

 .....

I want my ejs connect to socket and main.js. I just start to study js, so it is tricky for me. I really need some help.


来源: stackexchange

问:
Forcing a specific typing within a code block based on type testing which tsc is unable to understand
If I have a helper function

export function isDate (d) {
  return isObject(d) && objectToString(d) === '[object Date]'
}
```
<p>and in another function I call it</p>
<pre class="lang-js prettyprint-override"><code>function foo(opts: unknown) {
  if (isDate(opts)) {
    const y = opts.getFullYear()
    const m = opts.getMonth() + 1
</code>```

is there a way to let typescript know the opts argument is a Date within the block, without coercing every single reference to the opts argument with (opts as Date).getFullYear()

ContentLicense: CC BY-SA 4.0

Body:
If I have a helper function

export function isDate (d) {
  return isObject(d) && objectToString(d) === '[object Date]'
}

and in another function I call it

function foo(opts: unknown) {
  if (isDate(opts)) {
    const y = opts.getFullYear()
    const m = opts.getMonth() + 1

is there a way to let typescript know the opts argument is a Date within the block, without coercing every single reference to the opts argument with (opts as Date).getFullYear()


问:
Ionic pull to refresh locks entire page while refreshing
I am building an app using ReactJS and Ionic v6.

On a page I've made a "pull to refresh", it works well but the issue I am facing is that while it is refreshing, my entire page scroll is locked...

I can't navigate (scroll) through my page while refreshing

Here's how implemented the pull to refresh :

```<code> <IonPage>
      <IonContent>
        <IonRefresher
          slot="fixed"
          onIonRefresh={handleRefresh}
          pullFactor={0.5}
          pullMin={40}
        >
          <IonRefresherContent
            pullingIcon="arrow-down-outline"
            pullingText="Tirer pour actualiser..."
            refreshingSpinner="crescent"
          ></IonRefresherContent>
        </IonRefresher>

        <main className="content">
         ...
        </main>
      <IonContent/>
<IonPage/>
</code>```

Is there a way to make the pull to refresh "non-blocking" ?

Thanks for your help !

Body:
I am building an app using ReactJS and Ionic v6.

On a page I've made a "pull to refresh", it works well but the issue I am facing is that while it is refreshing, my entire page scroll is locked...

I can't navigate (scroll) through my page while refreshing

Here's how implemented the pull to refresh :

 <IonPage>
      <IonContent>
        <IonRefresher
          slot="fixed"
          onIonRefresh={handleRefresh}
          pullFactor={0.5}
          pullMin={40}
        >
          <IonRefresherContent
            pullingIcon="arrow-down-outline"
            pullingText="Tirer pour actualiser..."
            refreshingSpinner="crescent"
          ></IonRefresherContent>
        </IonRefresher>

         ...

      <IonContent/>
<IonPage/>

Is there a way to make the pull to refresh "non-blocking" ?

Thanks for your help !


问:
Angular Material Table displays uneven width on the first colum
I created a Material Table where I give the user the option to add or remove columns. The table can also sort, arrange columns, and has a sticky actions column. I want the table to take 100% of the available width space and scroll on the table when there are too many columns instead of fitting them to the screen size. The problem that I have is when only a few columns are displayed, for some reason the first column takes a lot more space then the other columns. I've tried many things and the only solution that I've found was making the table-layout: fixed but this will break the scrolling of overflow-x: scroll which is not what the users want. Any suggestions?

```<code><mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort cdkDropList cdkDropListOrientation="horizontal" (cdkDropListDropped)="drop($event)">
  <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
    <ng-container *ngIf="column !== 'Actions'; else action">
      <th [ngClass]="{'border': hasTableBorders}" mat-header-cell cdkDrag [hidden]="column == 'Id'" *matHeaderCellDef mat-sort-header>{{ column }}</th>
      <td [ngClass]="{'border': hasTableBorders}" mat-cell [hidden]="column == 'Id'" *matCellDef="let element">{{ element[column] | shorten:22 }}</td>
    </ng-container>
    <ng-template #action>
      <th mat-header-cell *matHeaderCellDef>Actions</th>
      <td mat-cell class="m-0 p-0" *matCellDef="let element">
        <h3 class="btn bi bi-pencil-fill" matTooltip="Quick Edit" (click)="onQuickEdit(element.Id)" [matTooltipPosition]="'above'"></h3>
        <h2 class="btn bi bi-eye-fill" matTooltip="View" (click)="onFullEdit(element.Id)" [matTooltipPosition]="'above'"></h2>
      </td>
    </ng-template>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr [ngClass]="{'alternate-row-colors': isAlternateRowColor}" mat-row *matRowDef="let row; columns: columnsToDisplay"></tr>
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
  </tr>
</mat-table>
</code>```

css

```<code>.mat-table {
  overflow-x: scroll;
  width: 100%;
}

.mat-cell, .mat-header-cell {
  word-wrap: initial;
  display: table-cell;
  padding: 0px 10px;
  line-break: unset;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  vertical-align: middle;
}

.mat-row,
.mat-header-row {
  display: table-row;
}
</code>```

Looks good with many columns

Bad display

Body:
I created a Material Table where I give the user the option to add or remove columns. The table can also sort, arrange columns, and has a sticky actions column. I want the table to take 100% of the available width space and scroll on the table when there are too many columns instead of fitting them to the screen size. The problem that I have is when only a few columns are displayed, for some reason the first column takes a lot more space then the other columns. I've tried many things and the only solution that I've found was making the table-layout: fixed but this will break the scrolling of overflow-x: scroll which is not what the users want. Any suggestions?

<mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort cdkDropList cdkDropListOrientation="horizontal" (cdkDropListDropped)="drop($event)">
  <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
    <ng-container *ngIf="column !== 'Actions'; else action">
      {{ column }}
      {{ element[column] | shorten:22 }}
    </ng-container>
    <ng-template #action>
      Actions

    </ng-template>
  </ng-container>

    No data matching the filter "{{input.value}}"

</mat-table>

css

.mat-table {
  overflow-x: scroll;
  width: 100%;
}

.mat-cell, .mat-header-cell {
  word-wrap: initial;
  display: table-cell;
  padding: 0px 10px;
  line-break: unset;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  vertical-align: middle;
}

.mat-row,
.mat-header-row {
  display: table-row;
}

Looks good with many columns

Bad display


问:
How can I code multiple values in a single line?
I have a data frame with a series of indicator variables whose responses determine the scoring of a second set of variables. What I have works, but it seems clunky.

Here's an example of what I've written:

```<code>ET.data$Q1_RUR <-NA
ET.data$Q1_RUR[Q1==1] <- 0.18831667304039
ET.data$Q1_RUR[Q1==2] <- -0.118123181164265
</code>```

I'd like to be able to condense it down to a single line, sort of like you can do in Stata:

```<code>recode Q1 (1=0.18831667304039)(2=-0.118123181164265)(else=.),generate(Q1_RUR)
</code>```

Any ideas on how I could further refine? Thanks!

Body:
I have a data frame with a series of indicator variables whose responses determine the scoring of a second set of variables. What I have works, but it seems clunky.

Here's an example of what I've written:

ET.data$Q1_RUR <-NA
ET.data$Q1_RUR[Q1==1] <- 0.18831667304039
ET.data$Q1_RUR[Q1==2] <- -0.118123181164265

I'd like to be able to condense it down to a single line, sort of like you can do in Stata:

recode Q1 (1=0.18831667304039)(2=-0.118123181164265)(else=.),generate(Q1_RUR)

Any ideas on how I could further refine? Thanks!


问:
How can I write a (very) basic custom QAbstractTextDocumentLayout subclass?
I'm trying to create a simple notepad-style Qt application. Since I think I might want a lot of control over exactly how text is rendered, I'm trying to write a custom QAbstractTextDocumentLayout class. The code below compiles and runs, but the text area is blank, no matter how much I type. The debug statements in my draw() function correctly show the entered text, so I know my input is in some form making it all the way to the draw() function, but it's not being rendered.

I just want to tweak this in a minimal way so I can at least see some text being rendered, even if the implementation is incomplete. I also haven't been able to find any documentation whatsoever on writing custom QAbstractTextDocumentLayout, so if anyone had a reference I'd also appreciate that.

main.cpp

#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QTextEdit>
#include <QKeyEvent>

#include "./DocumentLayout.cpp"

class MainContent : public QWidget
{
    Q_OBJECT

    QTextEdit textEdit;
    DocumentLayout layout;
public:
    MainContent() : textEdit(this), layout(textEdit.document())
    {
        int innerPadding = 20;
        textEdit.document()->setDocumentMargin(innerPadding);

        int textColor = 0xD8DEE9;
        int backgroundColor = 0x2E3440;
        int selectionColor = 0x2E3440;
        int selectionBackgroundColor = 0x81A1C1;

        QPalette palette = textEdit.palette();
        palette.setColor(QPalette::Base, QColor(backgroundColor));
        palette.setColor(QPalette::Text, QColor(textColor));
        palette.setColor(QPalette::Highlight, QColor(selectionBackgroundColor));
        palette.setColor(QPalette::HighlightedText, QColor(selectionColor));
        textEdit.setPalette(palette);

        textEdit.setFrameStyle(QFrame::NoFrame);

        textEdit.document()->setDocumentLayout(&layout);
    };

    void resizeEvent(QResizeEvent *event)
    {
        textEdit.setGeometry(0, 0, this->width(), this->height());
    }

    void keyPressEvent(QKeyEvent *event)
    {
        if (event->key() == Qt::Key_W && event->modifiers() == Qt::ControlModifier)
        {
            qApp->quit();
        }
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow window;
    window.setWindowTitle("Hello, world!");
    window.resize(400, 500);

    MainContent content;
    window.setCentralWidget(&content);

    window.show();
    return app.exec();
}

#include "main.moc"
```
<p><code>DocumentLayout.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QTextBlock>
#include <QDebug>

class DocumentLayout : public QAbstractTextDocumentLayout
{
public:
    DocumentLayout(QTextDocument *document) : QAbstractTextDocumentLayout(document)
    {
    }

    void draw(QPainter *painter, const PaintContext &context)
    {
        QTextDocument *document = this->document();
        QTextBlock block = document->begin();
        QPointF position(20, 20);

        painter->setPen(context.palette.color(QPalette::Text));
        QTextLayout *layout = block.layout();
        layout->draw(painter, position);
        position.ry() += layout->boundingRect().height();
        qDebug() << "drew" << block.text() << "at" << position;
    }

    int hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const
    {
        return 0;
    }

    int pageCount() const
    {
        return 1;
    }

    QSizeF documentSize() const
    {
        return QSizeF(400, 800);
    }

    QRectF frameBoundingRect(QTextFrame *frame) const
    {
        return QRectF(0, 0, 400, 800);
    }

    QRectF blockBoundingRect(const QTextBlock &block) const
    {
        return QRectF(0, 0, 400, 800);
    }

    void documentChanged(int from, int charsRemoved, int charsAdded)
    {
    }
};
</code>```

Body:
I'm trying to create a simple notepad-style Qt application. Since I think I might want a lot of control over exactly how text is rendered, I'm trying to write a custom QAbstractTextDocumentLayout class. The code below compiles and runs, but the text area is blank, no matter how much I type. The debug statements in my draw() function correctly show the entered text, so I know my input is in some form making it all the way to the draw() function, but it's not being rendered.

I just want to tweak this in a minimal way so I can at least see some text being rendered, even if the implementation is incomplete. I also haven't been able to find any documentation whatsoever on writing custom QAbstractTextDocumentLayout, so if anyone had a reference I'd also appreciate that.

main.cpp

#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QTextEdit>
#include <QKeyEvent>

#include "./DocumentLayout.cpp"

class MainContent : public QWidget
{
    Q_OBJECT

    QTextEdit textEdit;
    DocumentLayout layout;
public:
    MainContent() : textEdit(this), layout(textEdit.document())
    {
        int innerPadding = 20;
        textEdit.document()->setDocumentMargin(innerPadding);

        int textColor = 0xD8DEE9;
        int backgroundColor = 0x2E3440;
        int selectionColor = 0x2E3440;
        int selectionBackgroundColor = 0x81A1C1;

        QPalette palette = textEdit.palette();
        palette.setColor(QPalette::Base, QColor(backgroundColor));
        palette.setColor(QPalette::Text, QColor(textColor));
        palette.setColor(QPalette::Highlight, QColor(selectionBackgroundColor));
        palette.setColor(QPalette::HighlightedText, QColor(selectionColor));
        textEdit.setPalette(palette);

        textEdit.setFrameStyle(QFrame::NoFrame);

        textEdit.document()->setDocumentLayout(&layout);
    };

    void resizeEvent(QResizeEvent *event)
    {
        textEdit.setGeometry(0, 0, this->width(), this->height());
    }

    void keyPressEvent(QKeyEvent *event)
    {
        if (event->key() == Qt::Key_W && event->modifiers() == Qt::ControlModifier)
        {
            qApp->quit();
        }
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow window;
    window.setWindowTitle("Hello, world!");
    window.resize(400, 500);

    MainContent content;
    window.setCentralWidget(&content);

    window.show();
    return app.exec();
}

#include "main.moc"

DocumentLayout.cpp

#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QTextBlock>
#include <QDebug>

class DocumentLayout : public QAbstractTextDocumentLayout
{
public:
    DocumentLayout(QTextDocument *document) : QAbstractTextDocumentLayout(document)
    {
    }

    void draw(QPainter *painter, const PaintContext &context)
    {
        QTextDocument *document = this->document();
        QTextBlock block = document->begin();
        QPointF position(20, 20);

        painter->setPen(context.palette.color(QPalette::Text));
        QTextLayout *layout = block.layout();
        layout->draw(painter, position);
        position.ry() += layout->boundingRect().height();
        qDebug() << "drew" << block.text() << "at" << position;
    }

    int hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const
    {
        return 0;
    }

    int pageCount() const
    {
        return 1;
    }

    QSizeF documentSize() const
    {
        return QSizeF(400, 800);
    }

    QRectF frameBoundingRect(QTextFrame *frame) const
    {
        return QRectF(0, 0, 400, 800);
    }

    QRectF blockBoundingRect(const QTextBlock &block) const
    {
        return QRectF(0, 0, 400, 800);
    }

    void documentChanged(int from, int charsRemoved, int charsAdded)
    {
    }
};


问:
Reactive: executing many .existById() then executing some operations on collected data
I have many reactive operations .existById() to do,
then on the collected list I want to execute once some operations.
The problem is I don't know which reactive operators I should use, or how to rewrite this to archive the desirable effect.
Every try I coded effect execution of only one part of that code.

First try where no-reactive code weren't waiting on Cassandra repo:

```<code>//First part:
        signaturesFromFile.forEach(signatureFromFile -> {
            SignatureKey signatureKey = new SignatureKey(signatureFromFile.getProfileId(), signatureFromFile.getUserId(), signatureFromFile.getId());

            signatureRepositoryCassandra.existsById(signatureKey)
                    .map(exists -> {
                        if (!exists) {
                            notSavedSignatures.add(signatureFromFile);
                        }
                        return null;
                    }).subscribe();

        });

//Second part:
        String notSavedSignaturesListJson = convertSignaturesToJson(notSavedSignatures);

        String pathToNotSavedSigantures = NOT_TRANSFERRED_SIGNATURES_DIRECTORY + signatureFilename;
        saveIfFileNotExist(getUserIdFromFileName(signatureFilename), pathToNotSavedSigantures, notSavedSignaturesListJson);

        deleteTransferredByUserIdSignaturesFile(signatureFilename);

</code>```

The second idea was to close it in one reactive stream, but the problem recurred and the roles reversed - operations in the second part weren't executed

```<code>  Flux.fromIterable(signaturesFromFile).map(signatureFromFile -> {
            SignatureKey signatureKey = new SignatureKey(signatureFromFile.getProfileId(), signatureFromFile.getUserId(), signatureFromFile.getId());

//First part:
            signatureRepositoryCassandra.existsById(signatureKey)
                    .map(exists -> {
                        if (!exists) {
                            notSavedSignatures.add(signatureFromFile);
                        }
                        return null;
                    }).subscribe();
            return null;

        }).mergeWith(e -> {
//Second part:
            String notSavedSignaturesListJson = convertSignaturesToJson(notSavedSignatures);

            String pathToNotSavedSigantures = NOT_TRANSFERRED_SIGNATURES_DIRECTORY + signatureFilename;
            saveIfFileNotExist(getUserIdFromFileName(signatureFilename), pathToNotSavedSigantures, notSavedSignaturesListJson);

            deleteTransferredByUserIdSignaturesFile(signatureFilename);
        }).subscribe();

</code>```

I have a workaround for that problem ->
.findAll() and filter data instead of many executed .existById()
but I would like to resolve it with the correct operators ;)

Body:
I have many reactive operations .existById() to do,
then on the collected list I want to execute once some operations.
The problem is I don't know which reactive operators I should use, or how to rewrite this to archive the desirable effect.
Every try I coded effect execution of only one part of that code.

First try where no-reactive code weren't waiting on Cassandra repo:

//First part:
        signaturesFromFile.forEach(signatureFromFile -> {
            SignatureKey signatureKey = new SignatureKey(signatureFromFile.getProfileId(), signatureFromFile.getUserId(), signatureFromFile.getId());

            signatureRepositoryCassandra.existsById(signatureKey)
                    .map(exists -> {
                        if (!exists) {
                            notSavedSignatures.add(signatureFromFile);
                        }
                        return null;
                    }).subscribe();

        });

//Second part:
        String notSavedSignaturesListJson = convertSignaturesToJson(notSavedSignatures);

        String pathToNotSavedSigantures = NOT_TRANSFERRED_SIGNATURES_DIRECTORY + signatureFilename;
        saveIfFileNotExist(getUserIdFromFileName(signatureFilename), pathToNotSavedSigantures, notSavedSignaturesListJson);

        deleteTransferredByUserIdSignaturesFile(signatureFilename);

The second idea was to close it in one reactive stream, but the problem recurred and the roles reversed - operations in the second part weren't executed

  Flux.fromIterable(signaturesFromFile).map(signatureFromFile -> {
            SignatureKey signatureKey = new SignatureKey(signatureFromFile.getProfileId(), signatureFromFile.getUserId(), signatureFromFile.getId());

//First part:
            signatureRepositoryCassandra.existsById(signatureKey)
                    .map(exists -> {
                        if (!exists) {
                            notSavedSignatures.add(signatureFromFile);
                        }
                        return null;
                    }).subscribe();
            return null;

        }).mergeWith(e -> {
//Second part:
            String notSavedSignaturesListJson = convertSignaturesToJson(notSavedSignatures);

            String pathToNotSavedSigantures = NOT_TRANSFERRED_SIGNATURES_DIRECTORY + signatureFilename;
            saveIfFileNotExist(getUserIdFromFileName(signatureFilename), pathToNotSavedSigantures, notSavedSignaturesListJson);

            deleteTransferredByUserIdSignaturesFile(signatureFilename);
        }).subscribe();

I have a workaround for that problem ->
.findAll() and filter data instead of many executed .existById()
but I would like to resolve it with the correct operators ;)


问:
Using leaflet.markercluster with a Nuxt 3 app
I'm using Leaflet with Nuxt3, TypeScript and Composition API on a production website.
As we're getting more and more markers, I'd like to use leaflet.markercluster but I can't get how to make it work properly

Here's my setup :

leaflet.client.ts

import {
  LIcon,
  LMap,
  LMarker,
  LPopup,
  LTileLayer,
} from "@vue-leaflet/vue-leaflet";
import L from "leaflet";

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.component("LMap", LMap);
  nuxtApp.vueApp.component("LTileLayer", LTileLayer);
  nuxtApp.vueApp.component("LMarker", LMarker);
  nuxtApp.vueApp.component("LIcon", LIcon);
  nuxtApp.vueApp.component("LPopup", LPopup);

  return {
    provide: {
      L,
    },
  };
});

```
<p><code>Map.vue</code></p>
<pre class="lang-html prettyprint-override"><code><client-only>
   <l-map
       ref="locationsMap"
       :min-zoom="leafletOptions.minZoom"
       :max-zoom="leafletOptions.maxZoom"
       :zoom-animation="true"
       :zoom="leafletOptions.zoom"
       :center="leafletOptions.center"
       :useGlobalLeaflet="false"
       :options="{ tap: false }"
       @ready="onLeafletReady">
         <l-tile-layer :url="leafletOptions.url"/>
           <template v-for="location in locations"
                     :key="location.id">
             <l-marker
                :lat-lng="[location.attributes.lat, location.attributes.long]"
                v-if="location.attributes.active">
                  <div v-if="location.attributes.lat && location.attributes.long">
                    <l-popup class="text-center flex flex-col gap-y-4">
                     ...
                    </l-popup>
                    <l-icon>
                      ...
                    </l-icon>
                  </div>
              </l-marker>
            </template>
       </l-map>
        ...
</client-only>

<script setup lang="ts">
import {LIcon, LMap, LMarker, LPopup, LTileLayer} from "@vue-leaflet/vue-leaflet";
import "leaflet/dist/leaflet.css";

const leafletOptions = ref({
  url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
  minZoom: 5,
  maxZoom: 13,
  zoom: 5.5,
  map: null,
  center: [47.040182, 2.536054],
  bounds: null,
  overlayLocation: false,
  colors: ["#ED722E", "#F6BE00", "#979B0B", "#DA2C81"],
});

// Setup and api calls to get locations
</script>
</code>```

package.json

{
 ...,
 "depencencies": {
   "@vue-leaflet/vue-leaflet": "^0.7.0",
   "leaflet": "^1.9.3",
   "leaflet.markercluster": "^1.5.3",
 },
 "devDependencies": {
   "nuxt": "^3.0.0",
   "typescript": "^4.9.4"
   "@types/leaflet.markercluster": "^1.5.1",
 }
}
```
<p>The thing is, now I try to group my markers by adding <code>leaflet.markercluster</code>. So I added something like this :</p>
<p><code>leaflet.client.ts</code></p>
<pre class="lang-js prettyprint-override"><code>...
import "leaflet.markercluster";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";

export default defineNuxtPlugin((nuxtApp) => {
  ...

  return {
    provide: {
      L,
    },
  };
});
</code>```

But now I don't know what to do next. Using L.markerClusterGroup() as the official documentation says does not work as we get a 500 error for using a client-side method with ssr.

I also tried to directly import in my component with import :

Map.vue

import { MarkerClusterGroup } from 'leaflet.markercluster';

const markersGroup = ref(null);

...

const onLeafletReady = async () => {
  markersGroup.value = new MarkerClusterGroup() // NOT WORKING
  await nextTick();
  leafletObject.value = locationsMap.value;
  leafletReady.value = true;

  leafletObject.value.addLayer(markersGroup.value)
}
```

But we got the same problem as using L.anyMethod() by getting a 500 error.

I saw that Sam85 on this question has the package installed, but that was not the same problem. :/

Has anyone ever tried to make it work with Nuxt 3 ?

Body:
I'm using Leaflet with Nuxt3, TypeScript and Composition API on a production website.
As we're getting more and more markers, I'd like to use leaflet.markercluster but I can't get how to make it work properly

Here's my setup :

leaflet.client.ts

import {
  LIcon,
  LMap,
  LMarker,
  LPopup,
  LTileLayer,
} from "@vue-leaflet/vue-leaflet";
import L from "leaflet";

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.component("LMap", LMap);
  nuxtApp.vueApp.component("LTileLayer", LTileLayer);
  nuxtApp.vueApp.component("LMarker", LMarker);
  nuxtApp.vueApp.component("LIcon", LIcon);
  nuxtApp.vueApp.component("LPopup", LPopup);

  return {
    provide: {
      L,
    },
  };
});

Map.vue

<client-only>
   <l-map
       ref="locationsMap"
       :min-zoom="leafletOptions.minZoom"
       :max-zoom="leafletOptions.maxZoom"
       :zoom-animation="true"
       :zoom="leafletOptions.zoom"
       :center="leafletOptions.center"
       :useGlobalLeaflet="false"
       :options="{ tap: false }"
       @ready="onLeafletReady">
         <l-tile-layer :url="leafletOptions.url"/>
           <template v-for="location in locations"
                     :key="location.id">
             <l-marker
                :lat-lng="[location.attributes.lat, location.attributes.long]"
                v-if="location.attributes.active">

                    <l-popup class="text-center flex flex-col gap-y-4">
                     ...
                    </l-popup>
                    <l-icon>
                      ...
                    </l-icon>

              </l-marker>
            </template>
       </l-map>
        ...
</client-only>

package.json

{
 ...,
 "depencencies": {
   "@vue-leaflet/vue-leaflet": "^0.7.0",
   "leaflet": "^1.9.3",
   "leaflet.markercluster": "^1.5.3",
 },
 "devDependencies": {
   "nuxt": "^3.0.0",
   "typescript": "^4.9.4"
   "@types/leaflet.markercluster": "^1.5.1",
 }
}

The thing is, now I try to group my markers by adding leaflet.markercluster. So I added something like this :

leaflet.client.ts

...
import "leaflet.markercluster";
import "leaflet.markercluster/dist/MarkerCluster.css";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";

export default defineNuxtPlugin((nuxtApp) => {
  ...

  return {
    provide: {
      L,
    },
  };
});

But now I don't know what to do next. Using L.markerClusterGroup() as the official documentation says does not work as we get a 500 error for using a client-side method with ssr.

I also tried to directly import in my component with import :

Map.vue

import { MarkerClusterGroup } from 'leaflet.markercluster';

const markersGroup = ref(null);

...

const onLeafletReady = async () => {
  markersGroup.value = new MarkerClusterGroup() // NOT WORKING
  await nextTick();
  leafletObject.value = locationsMap.value;
  leafletReady.value = true;

  leafletObject.value.addLayer(markersGroup.value)
}

But we got the same problem as using L.anyMethod() by getting a 500 error.

I saw that Sam85 on this question has the package installed, but that was not the same problem. :/

Has anyone ever tried to make it work with Nuxt 3 ?


问:
ggplot with geom_line fails (need some advice)
I am applying the following codes to my original data to make a plot including ULN, LLN,Mu curves. As soon as running the following codes on my data, the function connect all the points and the output woud be:

So I was wondering how I can modify the following code to have the curves and solve this issue.

Here's the code:

```<code>library(gamlss)
library(gamlss.inf)
A<-lungFunction

m1 <- gamlss(slf ~ log(height) + pb(log(age)), sigma.fo =~pb(log(age)), nu.fix=T, nu.start=1, family = BCCGo(mu.link = "log"), data=A)

library(dplyr)
lms <-predictAll(m1,type="response")
TLC<-A$slf
pdf=A %>% mutate(Mu=lms$mu,
                 LLN=exp(log(lms$mu)+(log(1-1.645*lms$nu*lms$sigma))/lms$nu),
                 ULN=exp(log(lms$mu)+(log(1+1.645*lms$nu*lms$sigma))/lms$nu),
                 Z_score=((TLC/lms$mu)^(lms$nu)-1)/(lms$nu*lms$sigma),
                 pcPred=100*TLC/lms$mu,
                 cutof80=0.8*lms$mu)
pdf$ToleranceZscore=if_else(pdf$Z_score<(-1.645),
                            "Unacceptable",
                            "Acceptable")

pdf %>% ggplot(aes(x=age))+
  geom_point(aes(y=TLC),color="grey80")+
  geom_line(aes(y=ULN),se=F,color="blue",linetype=2)+
  geom_line(aes(y=LLN),se=F,color="red",linetype=2)+
  geom_line(aes(y=Mu),se=F,color="black")+
  geom_line(aes(y=cutof80),se=F,color="orange")+
  geom_point(aes(y=Mu,color=ToleranceZscore),size=2,alpha=0.6)+
  scale_color_brewer(palette = "Set1",direction = -1)+
  theme_bw()+ggtitle("Mu,%pred,LLN and ULN for Males")
</code>```

Body:
I am applying the following codes to my original data to make a plot including ULN, LLN,Mu curves. As soon as running the following codes on my data, the function connect all the points and the output woud be:

So I was wondering how I can modify the following code to have the curves and solve this issue.

Here's the code:

library(gamlss)
library(gamlss.inf)
A<-lungFunction

m1 <- gamlss(slf ~ log(height) + pb(log(age)), sigma.fo =~pb(log(age)), nu.fix=T, nu.start=1, family = BCCGo(mu.link = "log"), data=A)

library(dplyr)
lms <-predictAll(m1,type="response")
TLC<-A$slf
pdf=A %>% mutate(Mu=lms$mu,
                 LLN=exp(log(lms$mu)+(log(1-1.645*lms$nu*lms$sigma))/lms$nu),
                 ULN=exp(log(lms$mu)+(log(1+1.645*lms$nu*lms$sigma))/lms$nu),
                 Z_score=((TLC/lms$mu)^(lms$nu)-1)/(lms$nu*lms$sigma),
                 pcPred=100*TLC/lms$mu,
                 cutof80=0.8*lms$mu)
pdf$ToleranceZscore=if_else(pdf$Z_score<(-1.645),
                            "Unacceptable",
                            "Acceptable")

pdf %>% ggplot(aes(x=age))+
  geom_point(aes(y=TLC),color="grey80")+
  geom_line(aes(y=ULN),se=F,color="blue",linetype=2)+
  geom_line(aes(y=LLN),se=F,color="red",linetype=2)+
  geom_line(aes(y=Mu),se=F,color="black")+
  geom_line(aes(y=cutof80),se=F,color="orange")+
  geom_point(aes(y=Mu,color=ToleranceZscore),size=2,alpha=0.6)+
  scale_color_brewer(palette = "Set1",direction = -1)+
  theme_bw()+ggtitle("Mu,%pred,LLN and ULN for Males")


问:
Python-docx: How to do a Font size change to size 8 and style New Courier in python code
This script edits/replaces the dictionary strings. However, I have been unable to set the Font size is 8 and the style is New Courier. The output fons size is 10 which isn't desirable to edit all 100's doc.
Can someone help me with this Python-docx.</p>
```<code>import docx
import glob
import os
import shutil

# get all docx files in current directory
files = glob.glob(r'C:\Users\PycharmProjects\pythonProject1\MORsToppan\*.docx')

# create backup folder
if not os.path.exists('backup1'):
   os.makedirs('backup1')
# copy original files
for file in files:
    # copy files to backup folder
    shutil.copy(file, 'backup1')

# replacement dictionary
replacements = {'Date _04/25/19_':'Date _12/17/21_','Submitted
by_':'Submitted by_Lander Jr_','1X .gds file and mask order
documents':'customer .GDS and MOF for TP5X.','_XX_ ASM 6" 4X DUV
248nm (ASM5500 STEPPER/SCANNER)':'_XX_ ASM 6" 5X i-line 365nm
(ASM5500 STEPPER).'
,'60XXXX-118    B   26         4X    0.0200       X    X
1.400   0.080   5.800   0.040   0.040    DRY      MT  ':'60XXXX-118
A   26         5X    0.125     DK       Y      1.400   0.100
7.500   0.100   0.150    WET      MT  ' }

# loop through all files
for file in files:
    # open file
    doc = docx.Document(file)
# loop through all paragraphs
for para in doc.paragraphs:
    # for each of the words to be replaced, evaluate and do replacement
    for word in replacements.keys():
        # if paragraph contains the word to be replaced
        if word in para.text:
            # replace the word with the new one
            para.text = para.text.replace(word, replacements[word])
# save file
doc.save(file)

_______Input Data_____________

I.   BASIC INFORMATION:
 Die PN _60XXXX_    Product Number _U330PENG_    Date _01/05/23_
 Submitted by_Lander Jr_

II.  CHECKLIST OF WORK TO BE SUBMITTED TO MASK SHOP:
 1X .gds file and mask order documents

III. DATA:
 _XX_ 1X    _XX_ Metric    _XX_ .gds

IV.  PHOTOMASKS:
 _XX_ ASM 6" 4X DUV 248nm (ASM5500 STEPPER/SCANNER)

INFORMATION FOR EXTERNAL MASK SHOP ORDER
</code>```

Body:
This script edits/replaces the dictionary strings. However, I have been unable to set the Font size is 8 and the style is New Courier. The output fons size is 10 which isn't desirable to edit all 100's doc.
Can someone help me with this Python-docx.

import docx
import glob
import os
import shutil

# get all docx files in current directory
files = glob.glob(r'C:\Users\PycharmProjects\pythonProject1\MORsToppan\*.docx')

# create backup folder
if not os.path.exists('backup1'):
   os.makedirs('backup1')
# copy original files
for file in files:
    # copy files to backup folder
    shutil.copy(file, 'backup1')

# replacement dictionary
replacements = {'Date _04/25/19_':'Date _12/17/21_','Submitted
by_':'Submitted by_Lander Jr_','1X .gds file and mask order
documents':'customer .GDS and MOF for TP5X.','_XX_ ASM 6" 4X DUV
248nm (ASM5500 STEPPER/SCANNER)':'_XX_ ASM 6" 5X i-line 365nm
(ASM5500 STEPPER).'
,'60XXXX-118    B   26         4X    0.0200       X    X
1.400   0.080   5.800   0.040   0.040    DRY      MT  ':'60XXXX-118
A   26         5X    0.125     DK       Y      1.400   0.100
7.500   0.100   0.150    WET      MT  ' }

# loop through all files
for file in files:
    # open file
    doc = docx.Document(file)
# loop through all paragraphs
for para in doc.paragraphs:
    # for each of the words to be replaced, evaluate and do replacement
    for word in replacements.keys():
        # if paragraph contains the word to be replaced
        if word in para.text:
            # replace the word with the new one
            para.text = para.text.replace(word, replacements[word])
# save file
doc.save(file)

_______Input Data_____________

I.   BASIC INFORMATION:
 Die PN _60XXXX_    Product Number _U330PENG_    Date _01/05/23_
 Submitted by_Lander Jr_

II.  CHECKLIST OF WORK TO BE SUBMITTED TO MASK SHOP:
 1X .gds file and mask order documents

III. DATA:
 _XX_ 1X    _XX_ Metric    _XX_ .gds

IV.  PHOTOMASKS:
 _XX_ ASM 6" 4X DUV 248nm (ASM5500 STEPPER/SCANNER)

INFORMATION FOR EXTERNAL MASK SHOP ORDER


问:
How to apply gaussian blur to contour lines using Numpy and Skimage
I'm currently trying to create an image preprocessor that adds specific noise for AI training. In this case, I'm trying to add contour lines over the top of my input image that resemble sketch lines.

So far I have been able to get these lines drawn on my image, but they are very sharp and pixelated, which obviously doesn't resemble real artist-drawn lines. I need some way to apply a slight blur to soften these edges, but so far I have not been able to do this.

Here is a visual guide to what I am trying to achieve:

I need to find the contours in image (A) and draw them onto a new layer with alpha channel (B). I then need to blur these lines (C) and paste it back onto the original image (D).

Here is the section I'm having problems with:

```<code>    # Convert the image to a NumPy array
    augmented_image = np.array(augmented_image)
    augmented_shape = augmented_image.shape
    # Convert image back to color
    grey_image = color.rgb2gray(augmented_image)
    # Detect the contours of the image using the Canny edge detector
    edges = feature.canny(grey_image, sigma=3)

    # Create a blank image with dimensions 256 x 256
    blank_image = np.zeros((256, 256, 4))

    # Create a copy of the image to draw the contours on and convert to 4 layers rgba
    alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
    augmented_image = np.concatenate([augmented_image, alpha], axis=2)

    # Iterate over the contours
    for contour in measure.find_contours(edges, 0.8):
        # Set offset
        offset = 10

        # Select a random point along the contour
        point = np.random.randint(0, len(contour))
        start_row, start_col = contour[point]

        start_row = start_row + offset
        start_col = start_col + offset
        start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
        start_col = np.clip(start_col, 0, augmented_shape[0] - 1)

        # Select a random point along the contour that is not the same as the first point
        point = np.random.randint(0, len(contour))
        while point == start_row:
            point = np.random.randint(0, len(contour))
        end_row, end_col = contour[point]

        end_row = end_row + offset
        end_col = end_col + offset
        end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
        end_col = np.clip(end_col, 0, augmented_shape[0] - 1)

        # Draw the line on the image using the draw.line function
        rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
        blank_image[rr, cc] = 30

    # Smooth the contour lines using the gaussian function
    blank_image = filters.gaussian(blank_image, sigma=1)

    # Make sure image is same data-type
    blank_image = blank_image.astype(augmented_image.dtype)

    # Create a mask for the contour lines
    blank_alpha = blank_image[:, :, 3:]
    mask = np.any(blank_alpha > 0, axis=2)
    # Apply the smooth image to the masked region of the original image
    augmented_image[mask] = blank_image[mask]

    # Convert image back to 3 layers rgb
    augmented_image = augmented_image[:, :, :3]
</code>```

I know that the problem lies somewhere in the 'mask' variable definition. Something about it being a boolean type just pastes a line of pure black squares on my image rather than the expected blurred line. No amount of messing with layer order or adding extra layers to copy from has fixed this.

Doing this process without trying to blur the lines works great, minus the fact that it's very pixelated and doesn't fit the style of the training data. Blurring the image without trying to re-combine anything produces an adequate blurred line as well, however the entire image is blurred.

Here's what I can produce without the blurring process, and a rough idea of what I would like the final product to look like (made in Photoshop)

It's only when I try to mask and combine that this becomes a problem. I will post the full code below for anyone to run on their own system:

```<code>import random
import numpy as np
import skimage
from skimage.transform import rotate, resize
from skimage import draw, feature, color, measure, filters, util
from skimage.util import random_noise
import PIL
from PIL import Image
import os
import argparse
import cv2
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
import imghdr

# Set parser args
parser = argparse.ArgumentParser()
parser.add_argument("--dirty_dir", help="path to folder containing dirty images")
parser.add_argument("--clean_dir", help="path to folder containing clean images")
parser.add_argument("--dirty_savedir", help="path to dirty output folder")
parser.add_argument("--clean_savedir", help="path to clean output folder")

a = parser.parse_args()

# Set folder paths
dirty_dir = a.dirty_dir + '/'
clean_dir = a.clean_dir + '/'
dirty_savedir = a.dirty_savedir + '/'
clean_savedir = a.clean_savedir + '/'

print(f"Source Folder: {dirty_dir}")
print(f"Source Folder: {clean_dir}")
print(f"Output Folder: {dirty_savedir}")
print(f"Output Folder: {clean_savedir}")

def augment_image(image, filename, clean_dir):
    for i in range(8):
        # Create list for clean imgs
        clean_list = []
        # Randomly select a 256x256 region
        w, h = image.size[0], image.size[1]
        print(w,h)
        top = random.randint(0, h - 256)
        left = random.randint(0, w - 256)
        right = left + 256
        bottom = top + 256
        dims = [left, top, right, bottom]

        print(f'{filename} dimensions:{dims}')

        # Add dimensions to clean_list
        clean_list.extend(dims)

        augmented_image = image.crop((dims))
        print(f'{filename} shape: {augmented_image.size}')

        # Randomly rotate the image by 90, 180, or 270 degrees
        angle = random.choice([0, 90, 180, 270])
        augmented_image = augmented_image.rotate(angle)

        # Add angle to list
        clean_list.append(angle)

        # Randomly flip the image horizontally
        flip_lr = random.choice([True, False])
        if flip_lr == True:
            augmented_image = augmented_image.transpose(Image.FLIP_LEFT_RIGHT)
            clean_list.append("flip_lr")
        else:
            clean_list.append("none")
        # Randomly flip the image vertically
        flip_tb = random.choice([True, False])
        if flip_tb == True:
            augmented_image = augmented_image.transpose(Image.FLIP_TOP_BOTTOM)
            clean_list.append("flip_tb")
        else:
            clean_list.append("none")

        # Convert the image to a NumPy array
        augmented_image = np.array(augmented_image)
        augmented_shape = augmented_image.shape
        # Convert image back to color
        grey_image = color.rgb2gray(augmented_image)
        # Detect the contours of the image using the Canny edge detector
        edges = feature.canny(grey_image, sigma=3)

        # Create a blank image with dimensions 256 x 256
        blank_image = np.zeros((256, 256, 4))

        # Create a copy of the image to draw the contours on and convert to 4 layers rgba
        alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
        augmented_image = np.concatenate([augmented_image, alpha], axis=2)

        # Iterate over the contours
        for contour in measure.find_contours(edges, 0.8):
            # Set offset
            offset = 10

            # Select a random point along the contour
            point = np.random.randint(0, len(contour))
            start_row, start_col = contour[point]

            start_row = start_row + offset
            start_col = start_col + offset
            start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
            start_col = np.clip(start_col, 0, augmented_shape[0] - 1)

            # Select a random point along the contour that is not the same as the first point
            point = np.random.randint(0, len(contour))
            while point == start_row:
                point = np.random.randint(0, len(contour))
            end_row, end_col = contour[point]

            end_row = end_row + offset
            end_col = end_col + offset
            end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
            end_col = np.clip(end_col, 0, augmented_shape[0] - 1)

            # Draw the line on the image using the draw.line function
            rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
            blank_image[rr, cc] = 30

        # Smooth the contour lines using the gaussian function
        blank_image = filters.gaussian(blank_image, sigma=1)

        # Make sure image is same data-type
        blank_image = blank_image.astype(augmented_image.dtype)

        # Create a mask for the contour lines
        blank_alpha = blank_image[:, :, 3:]
        mask = np.any(blank_alpha > 0, axis=2)
        # Apply the smooth image to the masked region of the original image
        augmented_image[mask] = blank_image[mask]

        # Convert image back to 3 layers rgb
        augmented_image = augmented_image[:, :, :3]

        ## Add more noise types (lines, wrinkles, color)/make noise random chance to occur ##
        # Add random noise to the image
        noise = random_noise(augmented_image, mode='pepper', amount=0.011)

        # Convert the noisy image back to a PIL image
        augmented_image = np.random.random_sample(augmented_image.shape) * 255
        augmented_image = np.array(255 * noise, dtype=np.uint8)
        augmented_image = Image.fromarray(augmented_image)

        # Save file
        augmented_image.save(dirty_savedir + '_' + str(i) + '_' + filename)

        print(clean_list)

        # Function to mirror edits onto clean images
        def clean_aug(clean_dir, clean_list):
            # Open clean directory
            for filename in os.listdir(f"{clean_dir}"):
                # Rule out any weird Mac files
                if not filename.startswith("._"):
                    with Image.open(clean_dir + filename) as image:
                        # Define clean dimensions
                        clean_dims = clean_list[0:4]
                        # Crop image
                        clean_augmented = image.crop((clean_dims))
                        # Rotate clean image
                        clean_augmented = clean_augmented.rotate(clean_list[4])
                        # Flip clean image
                        if clean_list[5] == 'flip_lr':
                            clean_augmented = clean_augmented.transpose(Image.FLIP_LEFT_RIGHT)
                        if clean_list[6] == 'flip_tb':
                            clean_augmented = clean_augmented.transpose(Image.FLIP_TOP_BOTTOM)
                        # Save clean images
                        clean_augmented.save(clean_savedir + '_' + str(i) + '_' + filename)

                        print("Clean alterations copied successfully")

        clean_aug(clean_dir, clean_list)

# Clean up unnecessary files
def file_scrub():
    dirty_dir = dirty_savedir
    image_extensions = [".png", ".jpg"]  # add there all your images file extensions

    img_type_accepted_by_tf = ["bmp", "gif", "jpeg", "png"]
    for filepath in Path(dirty_dir).rglob("*"):
        if filepath.suffix.lower() in image_extensions:
            img_type = imghdr.what(filepath)
            if img_type is None:
                print(f"{filepath} is not an image")
            elif img_type not in img_type_accepted_by_tf:
                print(f"{filepath} is a {img_type}, not accepted by TensorFlow")

def image_aug(dirty_dir, clean_dir):
    for filename in os.listdir(f"{dirty_dir}"):
        # Check if the filename starts with "._"
        if not filename.startswith("._"):
            with Image.open(dirty_dir + filename) as image:
                # Open the image
                augment_image(image, filename, clean_dir)

image_aug(dirty_dir, clean_dir)
file_scrub()
</code>```

Apologies for the cumbersome codebase. I just wanted to minimize the risk of discrepancies arising from an attempt at concatenating my script. If there is any clarification I can provide please let me know!

Body:
I'm currently trying to create an image preprocessor that adds specific noise for AI training. In this case, I'm trying to add contour lines over the top of my input image that resemble sketch lines.

So far I have been able to get these lines drawn on my image, but they are very sharp and pixelated, which obviously doesn't resemble real artist-drawn lines. I need some way to apply a slight blur to soften these edges, but so far I have not been able to do this.

Here is a visual guide to what I am trying to achieve:

I need to find the contours in image (A) and draw them onto a new layer with alpha channel (B). I then need to blur these lines (C) and paste it back onto the original image (D).

Here is the section I'm having problems with:

    # Convert the image to a NumPy array
    augmented_image = np.array(augmented_image)
    augmented_shape = augmented_image.shape
    # Convert image back to color
    grey_image = color.rgb2gray(augmented_image)
    # Detect the contours of the image using the Canny edge detector
    edges = feature.canny(grey_image, sigma=3)

    # Create a blank image with dimensions 256 x 256
    blank_image = np.zeros((256, 256, 4))

    # Create a copy of the image to draw the contours on and convert to 4 layers rgba
    alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
    augmented_image = np.concatenate([augmented_image, alpha], axis=2)

    # Iterate over the contours
    for contour in measure.find_contours(edges, 0.8):
        # Set offset
        offset = 10

        # Select a random point along the contour
        point = np.random.randint(0, len(contour))
        start_row, start_col = contour[point]

        start_row = start_row + offset
        start_col = start_col + offset
        start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
        start_col = np.clip(start_col, 0, augmented_shape[0] - 1)

        # Select a random point along the contour that is not the same as the first point
        point = np.random.randint(0, len(contour))
        while point == start_row:
            point = np.random.randint(0, len(contour))
        end_row, end_col = contour[point]

        end_row = end_row + offset
        end_col = end_col + offset
        end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
        end_col = np.clip(end_col, 0, augmented_shape[0] - 1)

        # Draw the line on the image using the draw.line function
        rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
        blank_image[rr, cc] = 30

    # Smooth the contour lines using the gaussian function
    blank_image = filters.gaussian(blank_image, sigma=1)

    # Make sure image is same data-type
    blank_image = blank_image.astype(augmented_image.dtype)

    # Create a mask for the contour lines
    blank_alpha = blank_image[:, :, 3:]
    mask = np.any(blank_alpha > 0, axis=2)
    # Apply the smooth image to the masked region of the original image
    augmented_image[mask] = blank_image[mask]

    # Convert image back to 3 layers rgb
    augmented_image = augmented_image[:, :, :3]

I know that the problem lies somewhere in the 'mask' variable definition. Something about it being a boolean type just pastes a line of pure black squares on my image rather than the expected blurred line. No amount of messing with layer order or adding extra layers to copy from has fixed this.

Doing this process without trying to blur the lines works great, minus the fact that it's very pixelated and doesn't fit the style of the training data. Blurring the image without trying to re-combine anything produces an adequate blurred line as well, however the entire image is blurred.

Here's what I can produce without the blurring process, and a rough idea of what I would like the final product to look like (made in Photoshop)

It's only when I try to mask and combine that this becomes a problem. I will post the full code below for anyone to run on their own system:

import random
import numpy as np
import skimage
from skimage.transform import rotate, resize
from skimage import draw, feature, color, measure, filters, util
from skimage.util import random_noise
import PIL
from PIL import Image
import os
import argparse
import cv2
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
import imghdr

# Set parser args
parser = argparse.ArgumentParser()
parser.add_argument("--dirty_dir", help="path to folder containing dirty images")
parser.add_argument("--clean_dir", help="path to folder containing clean images")
parser.add_argument("--dirty_savedir", help="path to dirty output folder")
parser.add_argument("--clean_savedir", help="path to clean output folder")

a = parser.parse_args()

# Set folder paths
dirty_dir = a.dirty_dir + '/'
clean_dir = a.clean_dir + '/'
dirty_savedir = a.dirty_savedir + '/'
clean_savedir = a.clean_savedir + '/'

print(f"Source Folder: {dirty_dir}")
print(f"Source Folder: {clean_dir}")
print(f"Output Folder: {dirty_savedir}")
print(f"Output Folder: {clean_savedir}")

def augment_image(image, filename, clean_dir):
    for i in range(8):
        # Create list for clean imgs
        clean_list = []
        # Randomly select a 256x256 region
        w, h = image.size[0], image.size[1]
        print(w,h)
        top = random.randint(0, h - 256)
        left = random.randint(0, w - 256)
        right = left + 256
        bottom = top + 256
        dims = [left, top, right, bottom]

        print(f'{filename} dimensions:{dims}')

        # Add dimensions to clean_list
        clean_list.extend(dims)

        augmented_image = image.crop((dims))
        print(f'{filename} shape: {augmented_image.size}')

        # Randomly rotate the image by 90, 180, or 270 degrees
        angle = random.choice([0, 90, 180, 270])
        augmented_image = augmented_image.rotate(angle)

        # Add angle to list
        clean_list.append(angle)

        # Randomly flip the image horizontally
        flip_lr = random.choice([True, False])
        if flip_lr == True:
            augmented_image = augmented_image.transpose(Image.FLIP_LEFT_RIGHT)
            clean_list.append("flip_lr")
        else:
            clean_list.append("none")
        # Randomly flip the image vertically
        flip_tb = random.choice([True, False])
        if flip_tb == True:
            augmented_image = augmented_image.transpose(Image.FLIP_TOP_BOTTOM)
            clean_list.append("flip_tb")
        else:
            clean_list.append("none")

        # Convert the image to a NumPy array
        augmented_image = np.array(augmented_image)
        augmented_shape = augmented_image.shape
        # Convert image back to color
        grey_image = color.rgb2gray(augmented_image)
        # Detect the contours of the image using the Canny edge detector
        edges = feature.canny(grey_image, sigma=3)

        # Create a blank image with dimensions 256 x 256
        blank_image = np.zeros((256, 256, 4))

        # Create a copy of the image to draw the contours on and convert to 4 layers rgba
        alpha = np.ones((augmented_image.shape[0], augmented_image.shape[1], 1), dtype=augmented_image.dtype) * 255
        augmented_image = np.concatenate([augmented_image, alpha], axis=2)

        # Iterate over the contours
        for contour in measure.find_contours(edges, 0.8):
            # Set offset
            offset = 10

            # Select a random point along the contour
            point = np.random.randint(0, len(contour))
            start_row, start_col = contour[point]

            start_row = start_row + offset
            start_col = start_col + offset
            start_row = np.clip(start_row, 0, augmented_shape[0] - 1)
            start_col = np.clip(start_col, 0, augmented_shape[0] - 1)

            # Select a random point along the contour that is not the same as the first point
            point = np.random.randint(0, len(contour))
            while point == start_row:
                point = np.random.randint(0, len(contour))
            end_row, end_col = contour[point]

            end_row = end_row + offset
            end_col = end_col + offset
            end_row = np.clip(end_row, 0, augmented_shape[0] - 1)
            end_col = np.clip(end_col, 0, augmented_shape[0] - 1)

            # Draw the line on the image using the draw.line function
            rr, cc = draw.line(int(start_row), int(start_col), int(end_row), int(end_col))
            blank_image[rr, cc] = 30

        # Smooth the contour lines using the gaussian function
        blank_image = filters.gaussian(blank_image, sigma=1)

        # Make sure image is same data-type
        blank_image = blank_image.astype(augmented_image.dtype)

        # Create a mask for the contour lines
        blank_alpha = blank_image[:, :, 3:]
        mask = np.any(blank_alpha > 0, axis=2)
        # Apply the smooth image to the masked region of the original image
        augmented_image[mask] = blank_image[mask]

        # Convert image back to 3 layers rgb
        augmented_image = augmented_image[:, :, :3]

        ## Add more noise types (lines, wrinkles, color)/make noise random chance to occur ##
        # Add random noise to the image
        noise = random_noise(augmented_image, mode='pepper', amount=0.011)

        # Convert the noisy image back to a PIL image
        augmented_image = np.random.random_sample(augmented_image.shape) * 255
        augmented_image = np.array(255 * noise, dtype=np.uint8)
        augmented_image = Image.fromarray(augmented_image)

        # Save file
        augmented_image.save(dirty_savedir + '_' + str(i) + '_' + filename)

        print(clean_list)

        # Function to mirror edits onto clean images
        def clean_aug(clean_dir, clean_list):
            # Open clean directory
            for filename in os.listdir(f"{clean_dir}"):
                # Rule out any weird Mac files
                if not filename.startswith("._"):
                    with Image.open(clean_dir + filename) as image:
                        # Define clean dimensions
                        clean_dims = clean_list[0:4]
                        # Crop image
                        clean_augmented = image.crop((clean_dims))
                        # Rotate clean image
                        clean_augmented = clean_augmented.rotate(clean_list[4])
                        # Flip clean image
                        if clean_list[5] == 'flip_lr':
                            clean_augmented = clean_augmented.transpose(Image.FLIP_LEFT_RIGHT)
                        if clean_list[6] == 'flip_tb':
                            clean_augmented = clean_augmented.transpose(Image.FLIP_TOP_BOTTOM)
                        # Save clean images
                        clean_augmented.save(clean_savedir + '_' + str(i) + '_' + filename)

                        print("Clean alterations copied successfully")

        clean_aug(clean_dir, clean_list)

# Clean up unnecessary files
def file_scrub():
    dirty_dir = dirty_savedir
    image_extensions = [".png", ".jpg"]  # add there all your images file extensions

    img_type_accepted_by_tf = ["bmp", "gif", "jpeg", "png"]
    for filepath in Path(dirty_dir).rglob("*"):
        if filepath.suffix.lower() in image_extensions:
            img_type = imghdr.what(filepath)
            if img_type is None:
                print(f"{filepath} is not an image")
            elif img_type not in img_type_accepted_by_tf:
                print(f"{filepath} is a {img_type}, not accepted by TensorFlow")

def image_aug(dirty_dir, clean_dir):
    for filename in os.listdir(f"{dirty_dir}"):
        # Check if the filename starts with "._"
        if not filename.startswith("._"):
            with Image.open(dirty_dir + filename) as image:
                # Open the image
                augment_image(image, filename, clean_dir)

image_aug(dirty_dir, clean_dir)
file_scrub()

Apologies for the cumbersome codebase. I just wanted to minimize the risk of discrepancies arising from an attempt at concatenating my script. If there is any clarification I can provide please let me know!


问:
Android Studio Setup Wizard - Can't choose Virtual Device
Image of problem: Android Studio refuses Virtual Device

Android Virtual Device is installed with the Android Studio download and should say "Installed," but instead, it says "unavailable."

I'm returning from a three year code hiatus and was thinking of diving into React Native, but man did I just step into something odd that I must ask you about.

In the Setup Wizard for Android studio, it says the Android Virtual Device can't be clicked and says "unavailable."

I have tried re-downloading Android Studio both with downloading the virtual device and without, same problem.

I can't seem to find anything about it across the internet, rather the problems might be when it's up and running not in the Wizard.

Anyone got any ideas?


问:
How to make flutter application a default home launcher in android
I want to make my flutter app default home launcher, i have added category Home and Default inside intent filter in AndroidManifest.xml.

Now i when i press home button in my android i am not getting popup to choose from default home launcher.
How to get the popup where a user can choose to make it a default home launcher.

Following the artile on Make Your Own Custom Android Launcher using Flutter  i have added the below code to my AndroidManifest.xml

<category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" />

I am not getting any prompt/popup to use Launcher as home.

Please Help


问:
How do I correct a Rails cron.log error showing it can't find bundler 2.4.3 when I do have bundler 2.4.3?
Newbie, I'm trying to run a first time cron job in Rails 7 with whenever gem. I get the following error in the cron.log:

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:283:in `find_spec_for_exe': Could not find 'bundler' (2.4.3) required by your /Users/myname/mysite/Gemfile.lock. (Gem::GemNotFoundException)
To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:2.4.3`
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:302:in `activate_bin_path'
    from /usr/bin/bundle:23:in `<main>'
</code>```

I have this sample.rake:

```<code>namespace :sample do
  desc "saying hi to cron"
  task test: :developement do
    puts 'hi cron'
  end

end
</code>```

And this schedule.rb:

```<code>set :output, "log/cron.log"

 every 1.minute do
  rake 'sample:test'
 end
</code>```

gem list | grep bundle
bundler (2.4.3)

bundler -v
Bundler version 2.4.3

I have run 'bundle update --bundler` but it does nothing.
I have updated Homebrew, it does nothing.
any help?

Body:
Newbie, I'm trying to run a first time cron job in Rails 7 with whenever gem. I get the following error in the cron.log:

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:283:in `find_spec_for_exe': Could not find 'bundler' (2.4.3) required by your /Users/myname/mysite/Gemfile.lock. (Gem::GemNotFoundException)
To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:2.4.3`
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems.rb:302:in `activate_bin_path'
    from /usr/bin/bundle:23:in `'

I have this sample.rake:

namespace :sample do
  desc "saying hi to cron"
  task test: :developement do
    puts 'hi cron'
  end

end

And this schedule.rb:

set :output, "log/cron.log"

 every 1.minute do
  rake 'sample:test'
 end

gem list | grep bundle
bundler (2.4.3)

bundler -v
Bundler version 2.4.3

I have run 'bundle update --bundler` but it does nothing.
I have updated Homebrew, it does nothing.
any help?


问:
Vuejs v-calendar
My Dispatch Calendar

I am developing a scheduling calendar that displays each employee and the task assigned to them. I need help in changing the employee axis with the timeline. Similar to the following picture:
Desired Result

V-calendar code:

<v-calendar
      category-show-all
      ref="calendar"
      event-overlap-mode="stack"
      v-model="filter.date"
      type="category"
      :categories="category.list"
      :events="category.events"
      :event-color="getEventColor"
      :now="minimumDate"
      @change="getEvents"
      :row-height=60
      :interval-height="20"
      @click:event="showEvent">
</v-calendar>
```

I am not sure how to change the axis of v-calendar

Title: Vuejs v-calendar

Body:
My Dispatch Calendar

I am developing a scheduling calendar that displays each employee and the task assigned to them. I need help in changing the employee axis with the timeline. Similar to the following picture:
Desired Result

V-calendar code:

<v-calendar
      category-show-all
      ref="calendar"
      event-overlap-mode="stack"
      v-model="filter.date"
      type="category"
      :categories="category.list"
      :events="category.events"
      :event-color="getEventColor"
      :now="minimumDate"
      @change="getEvents"
      :row-height=60
      :interval-height="20"
      @click:event="showEvent">
</v-calendar>

I am not sure how to change the axis of v-calendar


问:
Opensearch 2.4.1 - SQL plugin and Index Patterns
I have upgraded my Opensearch cluster from 1.3 to 2.4.1 (using RPM - just following the instructions on https://opensearch.org/) The cluster runs on openjdk 17.0.5 that comes with the RPM).

I use to be able to leverage the SQL plugin like so:

```<code>    curl --location --request POST 'https://my_cluster/_plugins/_sql' --header 'Content-Type: application/json'
   --data-raw '{ "query": "SELECT date, @timestamp, value FROM profiler_outputs-*", "fetch_size": 100}'
</code>```

But since I upgraded, I get:

```<code>    {'error':
         {'reason': 'There was internal problem at backend',
          'details': 'Index type [profiler_outputs-*] does not exist',
          'type': 'IllegalArgumentException'},
     'status': 500}
</code>```

If I use an actual index name, instead of a pattern, it works (aka 'profiler_outputs-2023-02-09').

If I use '_plugins/_sql?format=json' it also works - as in it gives me the result in json format.

It also works in csv. But somehow, in JDBC (default return format) it always errors out if I use an index pattern. Is this a bug or am I missing something? I need the JDBC format so that I can paginate the result.

Body:
I have upgraded my Opensearch cluster from 1.3 to 2.4.1 (using RPM - just following the instructions on https://opensearch.org/) The cluster runs on openjdk 17.0.5 that comes with the RPM).

I use to be able to leverage the SQL plugin like so:

    curl --location --request POST 'https://my_cluster/_plugins/_sql' --header 'Content-Type: application/json'
   --data-raw '{ "query": "SELECT date, @timestamp, value FROM profiler_outputs-*", "fetch_size": 100}'

But since I upgraded, I get:

    {'error':
         {'reason': 'There was internal problem at backend',
          'details': 'Index type [profiler_outputs-*] does not exist',
          'type': 'IllegalArgumentException'},
     'status': 500}

If I use an actual index name, instead of a pattern, it works (aka 'profiler_outputs-2023-02-09').

If I use '_plugins/_sql?format=json' it also works - as in it gives me the result in json format.

It also works in csv. But somehow, in JDBC (default return format) it always errors out if I use an index pattern. Is this a bug or am I missing something? I need the JDBC format so that I can paginate the result.


问:
Extract all text from node and child nodes excluding specific nodes
I have the following HTML:

```<code><div class="flex flex-wrap">
  <span>Final result </span>
  <strong>2:0</strong> (7:6 <div>
    <sup>5</sup>
  </div>, 6:1)
</div>
</code>```

I can extract all the text using:

```<code>string(//div[@class='flex flex-wrap'])
</code>```

However, I don't want extract the superscript text in the  tag. How would I do this?

Body:
I have the following HTML:

  Final result
  2:0 (7:6

    5

, 6:1)

I can extract all the text using:

string(//div[@class='flex flex-wrap'])

However, I don't want extract the superscript text in the  tag. How would I do this?


问:
Avoid Public Access To Download Files in Static Folder FLASK
I serve a webapp using Flask. I have authentication for every user wanting to access URLs. Still, I notice a user without authentication (a user who is not logged in) can download my files (including .csv files, images, and ... ) inside the static folder if they know the name of my files.
by typing:

```<code> <public-ip>/static/whatever.csv
</code>```

I am not able to avoid that. I need help to avoid users downloading my stuff without permission. Any help would be appreciated. Thanks

I changed the permission of the static folder. but still, the files are downloadable.

Body:
I serve a webapp using Flask. I have authentication for every user wanting to access URLs. Still, I notice a user without authentication (a user who is not logged in) can download my files (including .csv files, images, and ... ) inside the static folder if they know the name of my files.
by typing:

 <public-ip>/static/whatever.csv

I am not able to avoid that. I need help to avoid users downloading my stuff without permission. Any help would be appreciated. Thanks

I changed the permission of the static folder. but still, the files are downloadable.


问:
Creating models with the Layers API
Im trying to create a model in jupyter notebook due to most of tensorflows functions being depreciated im getting a NameError and SyntaxError with the following code below</p>
```<code>IMAGE_SIZE=256
BATCH_SIZE=32
CHANNELS=3

input_shape = (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS)
n_classes = 3

const model = tf.sequential({
 layers: [
   resize_and_rescale,
   data_augmentation,
   tf.keras.layers.Conv2D({inputShape: input_shape, units: 32, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({kernel_size=(3,3), units: 64, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({kernel_size=(3,3), units: 64, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Flatten()
   tf.layers.dense({units: 64, activation: 'relu'}),
   tf.layers.dense({n_classes, activation: 'softmax'}),
 ]
});`
model.build(input_shape=input_shape)
</code>```

Title: Creating models with the Layers API

Body:
Im trying to create a model in jupyter notebook due to most of tensorflows functions being depreciated im getting a NameError and SyntaxError with the following code below

IMAGE_SIZE=256
BATCH_SIZE=32
CHANNELS=3

input_shape = (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS)
n_classes = 3

const model = tf.sequential({
 layers: [
   resize_and_rescale,
   data_augmentation,
   tf.keras.layers.Conv2D({inputShape: input_shape, units: 32, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({kernel_size=(3,3), units: 64, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({kernel_size=(3,3), units: 64, activation: 'relu'}),
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Conv2D({(3,3), units: 64, activation: 'relu'})
   tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
   tf.keras.layers.Flatten()
   tf.layers.dense({units: 64, activation: 'relu'}),
   tf.layers.dense({n_classes, activation: 'softmax'}),
 ]
});`
model.build(input_shape=input_shape)


问:
Send notifications when app is closed - android
I'm making a location-based TODO notifying app.
One of it's main features - is to send a notification to the user - if he's close to one of the location he defined.

What I need to do is to listen to the user's location - even when the app is closed.

I have come across the idea of a foreground service (This are 2 of it's function):

```<code>@Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
        {
            startForegroundCustom();
        }
        else
        {
            startForeground(1, new Notification());
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startForegroundCustom()
    {
        // this is cause of the O api that requires this notification settings...

        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel
                (NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder
                (this, NOTIFICATION_CHANNEL_ID);
        Notification notification =
                notificationBuilder.setOngoing(true)
                .setContentTitle("Hello from remindify!")
                .setPriority(NotificationManager.IMPORTANCE_NONE)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .build();

        System.out.println(notification);
        startForeground(2, notification);
    }
</code>```

Basically the startForeground at the end start the "Timer" of the Service.

Problem - it HAS to display a notification. I checked, and there's no way to not display a notification. As said here - How to startForeground() without showing notification?

My question is - do I have an alternative? or do I have to use this foreground service?

TL;DR: I need a way to listen to the user's location and send him notifications, even when the app is closed - which isn't a ForegroundService.

Body:
I'm making a location-based TODO notifying app.
One of it's main features - is to send a notification to the user - if he's close to one of the location he defined.

What I need to do is to listen to the user's location - even when the app is closed.

I have come across the idea of a foreground service (This are 2 of it's function):

@Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
        {
            startForegroundCustom();
        }
        else
        {
            startForeground(1, new Notification());
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startForegroundCustom()
    {
        // this is cause of the O api that requires this notification settings...

        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel
                (NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder
                (this, NOTIFICATION_CHANNEL_ID);
        Notification notification =
                notificationBuilder.setOngoing(true)
                .setContentTitle("Hello from remindify!")
                .setPriority(NotificationManager.IMPORTANCE_NONE)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .build();

        System.out.println(notification);
        startForeground(2, notification);
    }

Basically the startForeground at the end start the "Timer" of the Service.

Problem - it HAS to display a notification. I checked, and there's no way to not display a notification. As said here - How to startForeground() without showing notification?

My question is - do I have an alternative? or do I have to use this foreground service?

TL;DR: I need a way to listen to the user's location and send him notifications, even when the app is closed - which isn't a ForegroundService.


问:
How to import modules in Web Worker?
I'm developing project using Node.js + TypeScript.

After launching main.ts it returns:

```<code>import { parentPort } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module
</code>```

main.ts

```<code>import { Worker } from 'worker_threads';

const worker = new Worker('./src/Workers/worker.ts');

worker.on('message', (data) => {
    console.log(data);
})

worker.postMessage('start');
</code>```

worker.ts

```<code>import { parentPort } from 'worker_threads';
import { broadcastService } from '../services/BroadcastService'

parentPort?.on('message', async (data: string) => {
    console.log(data);
    const currentBroadcasts = await broadcastService.startBroadcastsChecking();
    parentPort?.postMessage(currentBroadcasts);
})
</code>```

Tried:

changing file extension to .js (worker.ts -> worker.js)

new Worker('./src/Workers/broadcastsCheckingWorker.ts', { type: 'module' } as any) (main.ts)

```<code>import { parentPort } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module
</code>```

importScripts('../services/BroadcastService') (worker.js/worker.ts)

```<code>importScripts('../services/BroadcastService')
^
ReferenceError [Error]: importScripts is not defined
</code>```

adding "type": "module" to package.json

```<code>TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\Administrator\Desktop\lives-downloader-bot\src\server.ts
</code>```

Title: How to import modules in Web Worker?

Body:
I'm developing project using Node.js + TypeScript.

After launching main.ts it returns:

import { parentPort } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module

main.ts

import { Worker } from 'worker_threads';

const worker = new Worker('./src/Workers/worker.ts');

worker.on('message', (data) => {
    console.log(data);
})

worker.postMessage('start');

worker.ts

import { parentPort } from 'worker_threads';
import { broadcastService } from '../services/BroadcastService'

parentPort?.on('message', async (data: string) => {
    console.log(data);
    const currentBroadcasts = await broadcastService.startBroadcastsChecking();
    parentPort?.postMessage(currentBroadcasts);
})

Tried:

changing file extension to .js (worker.ts -> worker.js)

new Worker('./src/Workers/broadcastsCheckingWorker.ts', { type: 'module' } as any) (main.ts)

import { parentPort } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module

importScripts('../services/BroadcastService') (worker.js/worker.ts)

importScripts('../services/BroadcastService')
^
ReferenceError [Error]: importScripts is not defined

adding "type": "module" to package.json

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\Administrator\Desktop\lives-downloader-bot\src\server.ts


问:
I want to set the fetched data from firestore as initial value of useState
I want to set the fetched data from firestore as initial value of useState but it gives me undefined value
because I want to edit user profile and I'm not sure user edit which property I wanted to stay the other properties the same</p>
```<code>import React, { useState, useEffect } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { doc, onSnapshot } from "firebase/firestore";
import { auth, db } from '../../firebase';

export default function Form({ setEditForm }) {
    const [user, setUser] = useState([]);
    const [currentUser] = useAuthState(auth);

    // fetching user information from firestore
    useEffect(() => {
        const getUser = async () => {
            const docRef = doc(db, 'users', currentUser.uid)
            await onSnapshot(docRef, (doc) => {
                setUser({
                    ...doc.data(), id: doc.id
                })
            })
        }
        getUser()
    }, [])
    const [name, setName] = useState(user.firstName);
    const [surname, setSurname] = useState(user.surname);
    const [biograhpy, setBiography] = useState(user.biograhpy);
    const [location, setLocation] = useState(user.location);

    // the name is undefined why? I want to put the fetching data from firestore as initial value of use state but it's undefined
    console.log(`name ${name}`)

  );
}
</code>```

Body:
I want to set the fetched data from firestore as initial value of useState but it gives me undefined value
because I want to edit user profile and I'm not sure user edit which property I wanted to stay the other properties the same

import React, { useState, useEffect } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { doc, onSnapshot } from "firebase/firestore";
import { auth, db } from '../../firebase';

export default function Form({ setEditForm }) {
    const [user, setUser] = useState([]);
    const [currentUser] = useAuthState(auth);

    // fetching user information from firestore
    useEffect(() => {
        const getUser = async () => {
            const docRef = doc(db, 'users', currentUser.uid)
            await onSnapshot(docRef, (doc) => {
                setUser({
                    ...doc.data(), id: doc.id
                })
            })
        }
        getUser()
    }, [])
    const [name, setName] = useState(user.firstName);
    const [surname, setSurname] = useState(user.surname);
    const [biograhpy, setBiography] = useState(user.biograhpy);
    const [location, setLocation] = useState(user.location);

    // the name is undefined why? I want to put the fetching data from firestore as initial value of use state but it's undefined
    console.log(`name ${name}`)

  );
}


问:
Sencha ExtJs OAuth token expired - How to trigger load event for second time on store after OAuth access token expired
My application is using access/refresh tokens for session management and for the front end framework I'm using Sencha ExtJs 7.1.

There is a problem showing data when I refresh the access token and send the ajax request again.

I can see the correct data I want to display in the response after sending the original request for a second time, but none of the components are populated with data. I think it might have something to do with how the Sencha framework is sending Ajax requests or maybe I am not sending the request for a second time at the correct moment.

If it is helpful, the ajax requests are being triggered from store.load() events. These load events also have callbacks with necessary logic to be executed when the store is loaded.

Steps as follows:

Send request with expired access token

Receive a 401 response code

Request a new access token with my refresh token

Send the original ajax requests again

```<code>Ext.Ajax.on('requestexception', function (conn, response, options) {
if (response.status === 401) {
    if (!refreshTokenPromise) {
        refreshTokenPromise = Portal.model.Session.refreshToken()
            .then(session => {
                //save session information here...
                return session;
            })
            .always(() => {
                refreshTokenPromise = null;
            })
    }
}

refreshTokenPromise
    .then(() => {
        Ext.Ajax.request(options)
            .then(function (response, opts) {
                console.dir(response.responseJson);
            });
    })
</code>```

});

Body:
My application is using access/refresh tokens for session management and for the front end framework I'm using Sencha ExtJs 7.1.

There is a problem showing data when I refresh the access token and send the ajax request again.

I can see the correct data I want to display in the response after sending the original request for a second time, but none of the components are populated with data. I think it might have something to do with how the Sencha framework is sending Ajax requests or maybe I am not sending the request for a second time at the correct moment.

If it is helpful, the ajax requests are being triggered from store.load() events. These load events also have callbacks with necessary logic to be executed when the store is loaded.

Steps as follows:

Send request with expired access token

Receive a 401 response code

Request a new access token with my refresh token

Send the original ajax requests again

Ext.Ajax.on('requestexception', function (conn, response, options) {
if (response.status === 401) {
    if (!refreshTokenPromise) {
        refreshTokenPromise = Portal.model.Session.refreshToken()
            .then(session => {
                //save session information here...
                return session;
            })
            .always(() => {
                refreshTokenPromise = null;
            })
    }
}

refreshTokenPromise
    .then(() => {
        Ext.Ajax.request(options)
            .then(function (response, opts) {
                console.dir(response.responseJson);
            });
    })

});


问:
How to know if a smaller polygon is inside a bigger one using Geopandas?

Problem

Hi, we are working on an ETL that cleans geodataframes according to it's geometries, we're trying to match some geometries inside others. For that we try to use some Geopandas shapely functions like overlaps, contains and covers, but the only one that seems to work is overlaps, but it's not working the way that we need.

The image from above is our general shapes, these are the ones that we want to be over the other shapes.

What we need to do is to delete the shapes that are outside the green area, that is the shapes that we presented as general.

What we've tried

The main problem is that when we use the overlaps function it gets the result presented in the next image.

import geopandas as gpd
from ..config import db

def transform (gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
    locality_data = gpd.GeoDataFrame.from_postgis(sql='SELECT * FROM localities', con=db.engine, geom_col='geometry')
    for upz_index, upz in gdf.iterrows():
        if not upz['geometry'] is None:
            if not filter_data(upz, locality_data):
                gdf = gdf.drop(upz_index)
    gdf = gdf.reset_index()
    return gdf

def filter_data(upz_geodataframe: gpd.GeoDataFrame, locality_geodataframe: gpd.GeoDataFrame) -> bool:
    for locality_index, locality in locality_geodataframe.iterrows():
        print(f"upz: {upz_geodataframe['CMNOMUPLA']} - loc: {locality['CMNOMLOCAL']}")
        if locality['geometry'].overlaps(other=upz_geodataframe['geometry']):
            print('Overlaps')
            return True
    return False
```

We created the function filter_data to associate each gray shape to each green shape.

Body:
Problem

Hi, we are working on an ETL that cleans geodataframes according to it's geometries, we're trying to match some geometries inside others. For that we try to use some Geopandas shapely functions like overlaps, contains and covers, but the only one that seems to work is overlaps, but it's not working the way that we need.

The image from above is our general shapes, these are the ones that we want to be over the other shapes.

What we need to do is to delete the shapes that are outside the green area, that is the shapes that we presented as general.

What we've tried

The main problem is that when we use the overlaps function it gets the result presented in the next image.

import geopandas as gpd
from ..config import db

def transform (gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
    locality_data = gpd.GeoDataFrame.from_postgis(sql='SELECT * FROM localities', con=db.engine, geom_col='geometry')
    for upz_index, upz in gdf.iterrows():
        if not upz['geometry'] is None:
            if not filter_data(upz, locality_data):
                gdf = gdf.drop(upz_index)
    gdf = gdf.reset_index()
    return gdf

def filter_data(upz_geodataframe: gpd.GeoDataFrame, locality_geodataframe: gpd.GeoDataFrame) -> bool:
    for locality_index, locality in locality_geodataframe.iterrows():
        print(f"upz: {upz_geodataframe['CMNOMUPLA']} - loc: {locality['CMNOMLOCAL']}")
        if locality['geometry'].overlaps(other=upz_geodataframe['geometry']):
            print('Overlaps')
            return True
    return False

We created the function filter_data to associate each gray shape to each green shape.


问:
How to remove an object from array with reactjs
How can I remove an object from the attachment array?

So when I uploaded multiple images, I was able to upload images correctly but when it comes to remove an image, I got an error.

```<code>export default function App() {

  const attachments = [
    { id: 1, src: "asdadsa1" },
    { id: 2, src: "asdadsa2" },
    { id: 3, src: "asdadsa3" }
  ];

  const [state, dispatch] = useReducer(
    reducer,
    CARD_DEFAULTS,
    () => cardDocdument
  );

  function reducer(state, { type, value }) {
    switch (type) {
      case "setAttachments":
        return update(state, {
          attachments: { $set: [...state.attachments, value] }
        });
      default:
        throw new Error();
    }
  }

  const updateAttachments = useCallback(
    (value) => {
      if (value === attachments) return;
      dispatch({ type: "setAttachmentsState", value });
    },
    [attachments]
  );

  return (
    <div className="App">
      <Child updateAttachments={updateAttachments} attachments={attachments} />
    </div>
  );
}

</code>```
```<code>
import React from "react";

const Child = ({ updateAttachments, attachments }) => {

  const saveAttachment = (files) => {
    const {length: filesLength} = files;
    for (let i = 0; i < filesLength; i++) {
      .
      .
      .
        const newAttachmentObj = addAttachment(fileObj);
        updateAttachments(newAttachmentObj);
      }
    }
  };

  const handleDelete = (attachment) => {
    const newAttachObj = attachments.find(attachment => attachment.uuid !== attachment.uuid);
    updateAttachments(newAttachObj);
  }

  return (
    <>
      <p>upload images link</p>
      <button onClick={() => saveAttachment(files)}>Save images</button>
      {
        attachments.map((attachment) => (
          <div key={attachment.id}>
          <img src={attachment.src} />
          <p onClick={() => {handleDelete(attachment)}}>remove image</p>
          </div>
        ))
      }
    </>
  );
};

export default Child;

</code>```

So take a look at the code for saving images...

When users upload multiple images, there is a for loop, the updateAttachments gets called and pass image attachment object to set it to an array (attachments: { $set: [...state.attachments, value] })

But when I remove an image, how can I remove an object that is clicked and set a new array without that object?

Attempts

```<code>  const handleDelete = (attachment) => {
    const newAttachObj = attachments.filter(
          ({uuid}) => uuid !== attachment.uuid,
        );

        const {length: attachmentsLength} = newValues;
        for (let i = 0; i < attachmentsLength; i++) {
          const attachObj = newValues[i];
          updateAttachments(attachObj);
        }
  }

</code>```

This put the objected without one I clicked to the attachments array but added new objects after the objects already existing...

So when I removed third object ({ id: 3, src: "asdadsa3" }), this is what I see in the attachment array.
Btw id is generated randomly so see src are duplicated.

```<code>[
    { id: 1, src: "asdadsa1" },
    { id: 2, src: "asdadsa2" },
    { id: 3, src: "asdadsa1" },
    { id: 4, src: "asdadsa2" },
]
</code>```

Body:
How can I remove an object from the attachment array?

So when I uploaded multiple images, I was able to upload images correctly but when it comes to remove an image, I got an error.

export default function App() {

  const attachments = [
    { id: 1, src: "asdadsa1" },
    { id: 2, src: "asdadsa2" },
    { id: 3, src: "asdadsa3" }
  ];

  const [state, dispatch] = useReducer(
    reducer,
    CARD_DEFAULTS,
    () => cardDocdument
  );

  function reducer(state, { type, value }) {
    switch (type) {
      case "setAttachments":
        return update(state, {
          attachments: { $set: [...state.attachments, value] }
        });
      default:
        throw new Error();
    }
  }

  const updateAttachments = useCallback(
    (value) => {
      if (value === attachments) return;
      dispatch({ type: "setAttachmentsState", value });
    },
    [attachments]
  );

  return (

      <Child updateAttachments={updateAttachments} attachments={attachments} />

  );
}

import React from "react";

const Child = ({ updateAttachments, attachments }) => {

  const saveAttachment = (files) => {
    const {length: filesLength} = files;
    for (let i = 0; i < filesLength; i++) {
      .
      .
      .
        const newAttachmentObj = addAttachment(fileObj);
        updateAttachments(newAttachmentObj);
      }
    }
  };

  const handleDelete = (attachment) => {
    const newAttachObj = attachments.find(attachment => attachment.uuid !== attachment.uuid);
    updateAttachments(newAttachObj);
  }

  return (
    <>

upload images link

      <button onClick={() => saveAttachment(files)}>Save images</button>
      {
        attachments.map((attachment) => (

 {handleDelete(attachment)}}>remove image

        ))
      }
    </>
  );
};

export default Child;

So take a look at the code for saving images...

When users upload multiple images, there is a for loop, the updateAttachments gets called and pass image attachment object to set it to an array (attachments: { $set: [...state.attachments, value] })

But when I remove an image, how can I remove an object that is clicked and set a new array without that object?

Attempts

  const handleDelete = (attachment) => {
    const newAttachObj = attachments.filter(
          ({uuid}) => uuid !== attachment.uuid,
        );

        const {length: attachmentsLength} = newValues;
        for (let i = 0; i < attachmentsLength; i++) {
          const attachObj = newValues[i];
          updateAttachments(attachObj);
        }
  }

This put the objected without one I clicked to the attachments array but added new objects after the objects already existing...

So when I removed third object ({ id: 3, src: "asdadsa3" }), this is what I see in the attachment array.
Btw id is generated randomly so see src are duplicated.

[
    { id: 1, src: "asdadsa1" },
    { id: 2, src: "asdadsa2" },
    { id: 3, src: "asdadsa1" },
    { id: 4, src: "asdadsa2" },
]